我正在开发一个由多个模型组成的应用程序。在我的model.py中的第二个模型中,它包含2-3个col。 char字段但在我的模板中,当我使用 {{form.billing_add}} 时,它不会在浏览器中显示任何文本输入
我的model.py文件是
来自django.db导入模型 来自django.contrib.auth.models导入用户
class Customer(models.Model):
user =models.OneToOneField(User)
birthday =models.DateField()
website =models.CharField(max_length=50)
store =models.CharField(max_length=50)
welcomemail =models.CharField(max_length=50)
def __unicode__(self):
return self.user
class Customer_check_attributes(models.Model):
customer = models.ForeignKey(Customer)
billing_add =models.CharField(max_length=50)
shipping_add =models.CharField(max_length=50)
payment_method =models.CharField(max_length=50)
shipping_method =models.CharField(max_length=50)
reward_points =models.CharField(max_length=50)
和我的form.py文件
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from customer_reg.models import Customer,Customer_check_attributes
class Registration_Form(ModelForm):
first_name = forms.CharField(label=(u'First Name'))
last_name = forms.CharField(label=(u'Last Name'))
username = forms.CharField(label=(u'User Name'))
email = forms.EmailField(label=(u'Email Address'))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
class Meta:
model=Customer
exclude=('user',)
答案 0 :(得分:1)
您似乎希望拥有一个包含多个模型属性的html表单。 因此,方法是为每个模型创建单独的表单,但通过一个视图和模板在一个页面上显示它,并在同一个中处理它。
这是示例
形式
#additional user attributes
class Registration_Form(ModelForm):
first_name = forms.CharField(label=(u'First Name'))
last_name = forms.CharField(label=(u'Last Name'))
username = forms.CharField(label=(u'User Name'))
email = forms.EmailField(label=(u'Email Address'))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
class Meta:
model = User
class CustomerForm(ModelForm):
class Meta:
model = Customer
exclude=('user',)
class Customer_check_attributesForm(ModelForm):
class Meta:
model = Customer_check_attributes
exclude=('user',)
视图:
def customer_add(request):
if request.method == 'POST':
uform = Registration_Form(request.POST)
cform = CustomerForm(request.POST)
caform = Customer_check_attributesForm(request.POST)
if uform.is_valid() :
...
user = uform.save()
if cform.is_valid() :
...
customer = cform.save()
if caform.is_valid() :
...
cattr = caform.save()
else:
uform = Registration_Form()
cform = CustomerForm()
caform = Customer_check_attributesForm()
ctx = { 'uform': uform, 'cform':cform, 'caform': caform }
return render_to_response('add_customer_template.html', ctx,
context_instance = RequestContext(request))
示例add_customer_template.html
<form>
{#other rendering logic#}
{{ uform.as_p }}
{{ cform.as_p }}
{{ caform.as_p }}
</form>
注意:这是一个指南代码。处理错误和更好的逻辑还有改进的余地。