django如何在表单中添加MinLengthValidator验证器

时间:2016-11-28 06:17:34

标签: django django-forms django-validation

我有一个搜索表单,我想验证输入'seach_word'至少有4个字母。我在尝试验证表单时收到此错误

必须先呈现响应内容,然后才能进行迭代。

#views.py
class SearchFormView(FormView):
    form_class = PostSearchForm
    template_name = 'lineup/post_search.html'

    def form_valid(self, form):
        schWord = form.cleaned_data['search_word']
        search_type = form.cleaned_data['search_type']
        context = {}

        if search_type == 'store':
            post_list = Store.objects.filter(
                  Q(cie_name__icontains=schWord)).distinct()
            context['object_type'] = 'store' 
            context['object_list'] = post_list 

        if search_type == 'city':
            post_list = Address.objects.filter(
                  Q(city__icontains=schWord)).distinct()
            context['object_type'] = 'city'
            context['object_list'] = post_list

        context['form'] = form
        context['search_term'] = schWord
        return render(self.request, self.template_name, context)

    def form_invalid(self, form):
        schWord = form.cleaned_data['search_word']
        messages.add_message(
         self.request, messages.WARNING, _('Please correct this...'))
        context =  super(SearchFormView, self).form_invalid(form)
        return render(self.request, self.template_name, context)

forms.py的内容

#forms.py
class PostSearchForm(forms.Form):
    SEARCH_TYPE_CHOICES = (
        ('city', 'city'),
        ('store', 'store'),
        ('product', 'product'),
        )
    search_type = forms.ChoiceField(choices=SEARCH_TYPE_CHOICES,  required=True)
    search_word = forms.CharField(label='Search Word',
                  validators=[MinLengthValidator(4)], required=True)
    '''
    def clean_search_word(self):
        cd = self.cleaned_data
        if len(cd['search_word']) < 4:
            raise forms.ValidationError('too short.')
        return cd['search_word']
    '''
    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
            Fieldset(
                '',
                Field('search_type', css_class='span6'),
                Field('search_word', css_class='span6'),
            ),
            FormActions(
                Submit('submit', 'Go', css_class='btn btn-primary')
            )
        )
        super(PostSearchForm, self).__init__(*args, **kwargs)

tracenack

Environment:


Request Method: POST
Request URL: http://localhost:8000/search/

Django Version: 1.10.3
Python Version: 3.5.2
Installed Applications:
['grappelli',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'debug_toolbar',
 'stripe',
 'vote',
 'django_messages',
 'pinax.notifications',
 'admin_honeypot',
 'easy_thumbnails',
 'django_extensions',
 'crispy_forms',
 'datetimewidget',
 'lineup',
 'allauth',
 'allauth.account',
 'allauth.socialaccount']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware',
 'django.middleware.locale.LocaleMiddleware']


File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/views/generic/edit.py" in post
  185.             return self.form_invalid(form)

File "/home/laptopguy/Documents/lineupNovember/lineup/views.py" in form_invalid
  58.         return render(self.request, self.template_name, context)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/loader.py" in render_to_string
  68.     return template.render(context, request)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/backends/django.py" in render
  64.         context = make_context(context, request, autoescape=self.backend.engine.autoescape)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/context.py" in make_context
  267.             context.push(original_context)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/context.py" in push
  59.         return ContextDict(self, *dicts, **kwargs)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/context.py" in __init__
  18.         super(ContextDict, self).__init__(*args, **kwargs)

File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/response.py" in __iter__
  123.                 'The response content must be rendered before it can be iterated over.'

Exception Type: ContentNotRenderedError at /search/
Exception Value: The response content must be rendered before it can be iterated over.

1 个答案:

答案 0 :(得分:2)

回溯显示您的问题出在form_invalid方法中。您正在将超类调用的结果捕获为context,并将其传递给render函数。但是超类方法返回响应,而不是上下文 - 它已经为你渲染了模板,你只需要返回它。

def form_invalid(self, form):
    schWord = form.cleaned_data['search_word']
    messages.add_message(
         self.request, messages.WARNING, _('Please correct this...'))
    return super(SearchFormView, self).form_invalid(form)