用ModelForm生成一个HTML

class CustomerForm(forms.ModelForm):
    class Meta:
        model = models.Customer
        fields = '__all__'
        error_messages = {
            'qq': {'required': '不能为空'},
            'course': {'required': '不能为空'}
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field_name, field in self.fields.items():   # self.fields是一个OrderedDict字典类型,
            # print(self.fields)       # OrderedDict([('qq', <django.forms.fields.CharField object at 0x0000022EB2AB2F10>)]
            if not isinstance(field, MultiSelectFormField):     # 判断field是不是MultiSelectFormField的一个类对象
                field.widget.attrs.update({'class': 'form-control'})    # field(对象).widget(属性).attrs(属性).update(方法)
            if isinstance(field, DateField):
                field.widget.attrs.update({'type': 'date'})


def add_edit_customer(request, cid=None):
    label = '编辑客户' if cid else '添加客户'
    customer_obj = models.Customer.objects.filter(pk=cid).first()
    if request.method == 'GET':
        customer_form = CustomerForm(instance=customer_obj) #instance=  Customer查到的实列对象
        return render(request, 'saleshtml/edit_customer.html', {'customer_form': customer_form, 'label': label})
    else:
        customer_form = CustomerForm(request.POST, instance=customer_obj)
        if customer_form.is_valid():
            customer_form.save()
            return redirect('customers')
        else:
            return render(request, 'saleshtml/edit_customer.html', {'customer_form': customer_form, 'label': label})

网页:

{% block Starter_Page %}
    {{ label }}
{% endblock %}

    <form action="" class="form-horizontal" method="post" novalidate="novalidate">
        {% csrf_token %}
        {% for field in customer_form %}
            <div class="form-group">
                <label for="{{ field.id_for_label }}" class="col-sm-2 control-label">{{ field.label }}</label>
                <div class="col-sm-6">
                    {{ field }}
                </div>
                <div class="col-sm-4">
                    {{ field.errors.0 }}
                </div>
            </div>
        {% endfor %}
        <button class="btn btn-primary">提交</button>
    </form>

forms.ModelChoiceField等from框显示指定的查询:

class ConsultRecordForm(forms.ModelForm):
    class Meta:
        model = models.ConsultRecord    # 指定对应的model里的表
        fields = '__all__'              # 指定字段(ConsultRecord中)
        exclude = ['delete_status', ]   # 排除某个字段
        
      """
        ModelForm在创建字段时,其中某些查询到多条数据的form会自动创建一个queryset属性,并查询出所有对应表的数据,例如默认生成:
            test = forms.ModelChoiceField(
                queryset=models.ConsultRecord.objects.all()
            )
        想要显示指定的查询数据,可以显示的给属性queryset赋值 ↓↓↓↓↓
      """ 

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field_name, field in self.fields.items():    
            # field_name:字段名,field:类对象 
            # field_name:customer
            # field: <django.forms.models.ModelChoiceField object at 0x000001A706C61970> 
            # field_type: <class 'django.forms.models.ModelChoiceField'>
            field.widget.attrs.update({'class': 'form-control'})
            if field_name == 'customer':
                field.queryset = models.Customer.objects.filter(consultant=request.user_obj)

 

posted @ 2021-03-03 13:24  笑而不语心自闲  阅读(76)  评论(0编辑  收藏  举报