我有一个大的形式来处理与Django。我的模型是如下Django窗体预加载模型数据
class MerchantContact(models.Model):
merchant = models.OneToOneField(MerchantProfile, related_name="merchant_contact")
ContactUsAddressLine1 =models.CharField(max_length=16)
ContactUsAddressLine2 =models.CharField(max_length=16)
ContactUsAddressCity =models.CharField(max_length=16)
ContactUsAddressState =models.CharField(max_length=4)
ContactUsAddressZip=models.CharField(max_length=16)
ContactUsPhone=models.CharField(max_length=16)
ContactUsAddressFax=models.CharField(max_length=16)
ContactUsEmail=models.CharField(max_length=64)
ContactUsBusinessHours=models.CharField(max_length=256)
我用下面的逻辑来填充表单
def merchantAccountInfo(request):
#check if data is already there or not
usr=UserProfile.objects.get(user_id=request.user.id)
merchant=MerchantProfile.objects.get(user_id=usr.id)
try:
mc=MerchantContact.objects.get(merchant_id=merchant.id)
formdata=MerchantContactForm(
{'id':mc.id,
'ContactUsAddressLine1':mc.ContactUsAddressLine1,
'ContactUsAddressLine2':mc.ContactUsAddressLine2,
'ContactUsAddressCity':mc.ContactUsAddressCity,
'ContactUsAddressState':mc.ContactUsAddressState,
'ContactUsAddressZip':mc.ContactUsAddressZip,
'ContactUsPhone':mc.ContactUsPhone,
'ContactUsAddressFax':mc.ContactUsAddressFax,
'ContactUsEmail':mc.ContactUsEmail,
'ContactUsBusinessHours':mc.ContactUsBusinessHours
}
)
except MerchantContact.DoesNotExist:
formdata=MerchantContactForm()
return render_to_response('account_info.html',locals(),context_instance=RequestContext(request))
上面的代码工作完美,但我担心的是,形式可以是具有30+场太大。直接传递每个字段将是太繁琐的方式..
任何其他替代方案来节省时间和代码行?
这是假设你已经创建了一个'ModelForm'而不是一个标准的'Form',但它应该是一个'ModelForm',如果它不是。 – 2012-08-17 14:11:27