Django表单字段验证无法正常工作

时间:2016-02-26 13:46:11

标签: python django

这是我的表格。

class POICreateForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(POICreateForm, self).__init__(*args, **kwargs)
        self.fields['latitude'].widget = HiddenInput()
        self.fields['longitude'].widget = HiddenInput()
        self.fields['picture'].required = True

    class Meta:
        fields = ['name', 'vip', 'category', 'place', 'latitude', 'longitude', 'picture', 'website', 'description',
                  'phone',
                  'email']
        model = PointOfInterest

    def clean(self):
        cleaned_data = super(POICreateForm, self).clean()
        pic = cleaned_data.get('picture', None)
        if not pic:
            msg = 'You must Choose an image'
            self.add_error('picture', msg)

        return cleaned_data

我已为required=True字段提供了picture,并且我覆盖了clean方法。 BUt都无法显示验证错误。

这是我的view

class POIFormCreateView(LoginRequiredMixin, CreateView):
    login_url = '/login/'
    model = PointOfInterest
    form_class = POICreateForm
    success_url = reverse_lazy('POIs')

    def post(self, request, *args, **kwargs):

        query_dict = request.POST.dict()
        super(POIFormCreateView, self).post(request, *args, **kwargs)
        filtered_dict = {i: j for i, j in query_dict.items() if i.endswith('day')}

        out = PointOfInterestQuery.create_or_update_open_hours(filtered_dict)
        if out:
            return HttpResponseRedirect(reverse('POIs'))
        return HttpResponse('Error :(')

template.html

{% extends 'base.html' %}
{% load crispy_forms_tags %}

{% block content %}
    <script type="text/javascript">

    </script>
    <h1>New Point Of Interest</h1>

    <form role="form" method="POST" action="/poi/add/" class="post-form form-horizontal"
          enctype="multipart/form-data" name="poi_create" onsubmit="return validateForm()">{% csrf_token %}
        <div class="container row">
            <div class="col-lg-6">
                <!-- customizing form -->
                {{ form|crispy }}
                <!-- End of customization -->
            </div>
            <div class="col-lg-6">
                <div id="map"></div>
                {% include 'open_hours.html' %}
            </div>
        </div>
                    <button type="submit" id="poi-submit" class="save btn btn-default btn-primary center-block">Save
                </button>
    </form>
    <div class="modal-footer"><a href="/poi/">
        <button type="button" class="btn btn-default btn-danger center-block">Cancel
        </button>
    </a></div>

{% endblock %}

1 个答案:

答案 0 :(得分:1)

您已覆盖post方法并完全避免使用该表单。所有这些逻辑都应该采用form_valid方法;允许CreateView执行表单验证的正常工作,并在表单无效时重新显示包含错误的页面,而如果表单有效则处理。

但请注意,您应该从表单的filtered_dict字典中获取值cleaned_data,而不是直接从request.POST填充。

class POIFormCreateView(LoginRequiredMixin, CreateView):
    login_url = '/login/'
    model = PointOfInterest
    form_class = POICreateForm
    success_url = reverse_lazy('POIs')

    def form_valid(self,form):
        super(POIFormCreateView, self).form_valid(form)
        filtered_dict = {i: j for i, j in self.request.POST.items() if i.endswith('day')}

        out = PointOfInterestQuery.create_or_update_open_hours(filtered_dict)
        if out:
            return HttpResponseRedirect(reverse('POIs'))
        return HttpResponse('Error :(')