用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>

 

上一篇:Django之ModelForm


下一篇:19-2 from和modelform的用法和介绍