如何在模板中添加django表单的ModelChoice字段

时间:2017-05-11 18:03:02

标签: python django

目前,我正在开发一个Web应用程序。我正在使用表单来渲染字段。我的应用程序中有多个ModelChoiceField。我在渲染ModelChoiceField时遇到错误。我做的是......

<div class="row">
      <div class="input-field col s6">
        {{ form.state }} 
        <label for="id_state">State</label>
        {{ form.country }} 
        <label for="id_country">Country</label>
      </div>
</div>

enter image description here 州和国家是两个ModelChoiceFields。它只显示标签,并且该字段不可见。但是当我检查元素时,我能够看到选择。但是在模板中它没有正确显示。可能是什么原因?

更新 表格

class CustomerForm(forms.Form):

    name = forms.CharField(label='Customer',max_length=250, required=True)
    image = forms.ImageField(label='Image')
    is_company = forms.BooleanField(label='Is comapany')
    company = forms.ModelChoiceField(queryset=Company.objects.all(), empty_label='Select company', label='Company')
    mobile = forms.IntegerField(label='Mobile')
    email = forms.EmailField(label='Email')
    street = forms.CharField(label='Lane',max_length=300)
    street2 = forms.CharField(label='Street',max_length=300)
    city = forms.CharField(label='City',max_length=250)
    state = forms.ModelChoiceField(queryset=State.objects.all(), empty_label='Select state', label='State')
    country = forms.ModelChoiceField(queryset=Country.objects.all(), empty_label='Select country' ,label='Country')
    zip = forms.IntegerField(label='Zip Code')
    note = forms.CharField(label='Internal Note',widget=forms.Textarea)
    date_create = forms.DateTimeField()

更新 视图

def form_view(request,customer_id):
    try:
        customer = Customer.obects.get(pk=pk)
    except Customer.DoesNotExist:
        raise Http404('Customer does not exist')
    else:
        data = {
            'name': customer.name,
            'image': customer.image,  
            'is_company': customer.is_company, 
            'company': customer.company, 
            'mobile': customer.mobile, 
            'email': customer.email,
            'street': customer.street, 
            'street2': customer.street2,
            'city': customer.city, 
            'state': customer.state, 
            'country': customer.country, 
            'zip': customer.zip,
            'note': customer.note,  
            }  
        customer_form = CustomerForm(data)
        context = {'form':customer_form}  
        return render(request, 'base/customer_form_view.html', context)

0 个答案:

没有答案