django上下文处理器表单在提交时不显示错误

时间:2017-12-14 15:44:22

标签: python django forms

我正在使用上下文处理器将表单呈现到我的项目中的基本模板,并且表单似乎工作正常,除了它没有显示所需字段为空白等的任何错误。页面即使没有填写字段,也只是重新加载。

之前我在其他项目中使用过这种方法,它工作得很好,但现在我无法弄清楚发生了什么以及为什么会这样。

这是我的 forms.py

from django import forms

class VersionSelectorForm(forms.Form):
    mode = forms.ChoiceField(widget=forms.RadioSelect(),
                             choices=(('live', 'Live'), ('history', 'History')),
                             initial='live',
                             required=True,
                             help_text='Required')
    date = forms.DateField(widget=forms.TextInput(attrs={'class': 'datepicker'}),
                           required=True,
                           help_text='required')

    def clean(self):
        cleaned_data = super(VersionSelectorForm, self).clean()
        mode = cleaned_data.get('mode')
        date = cleaned_data.get('date')

        if mode == 'history' and not date:
            msg = 'Date should be picked if \'History\' mode selected'
            self.add_error('date', msg)

view.py

from django.shortcuts import redirect
from .forms import VersionSelectorForm

def select_version(request): 
    if request.method == "POST": 
        form = VersionSelectorForm(request.POST) 
        if form.is_valid():
            print('I am valid')
            mode = form.cleaned_data["mode"]
            date = form.cleaned_data["date"]
            if mode == "History":
                request.session['selected_date'] = date
            else:
                request.session['selected_date'] = None
    else: 
        form = VersionSelectorForm() 
    return redirect(request.META['HTTP_REFERER']) 

context_processors.py

from .forms import VersionSelectorForm 

def VersionSelectorFormGlobal(request): 
    return {'version_selector_form': VersionSelectorForm()} 

urls.py:

from django.contrib import admin
from diagspecgen import views

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^select_version/$', views.select_version, name='select_version'),
]
来自base.html的

片段

<section><div>
            <form method="post" action="{% url 'select_version'%}">
                {% csrf_token %}
                {{ version_selector_form.as_p }}
                <button type="submit">Submit</button>
            </form>
        </div></section>

当然我已将'diagspecgen.context_processors.VersionSelectorFormGlobal'添加到 settings.py 中的 context_processors 列表中。

期待任何帮助,并提前感谢。

1 个答案:

答案 0 :(得分:0)

您不应该使用上下文处理器来呈现表单,而是将其传递给django快捷方式render函数。

你可以这样做:

def select_version(request): 
    if request.method == "POST": 
        form = VersionSelectorForm(request.POST) 
        if form.is_valid():
            print('I am valid')
            mode = form.cleaned_data["mode"]
            date = form.cleaned_data["date"]
            if mode == "History":
                request.session['selected_date'] = date
            else:
                request.session['selected_date'] = None
    else: 
        form = VersionSelectorForm() 
    return render(request, 'template.html', {'form': form}) 

请勿忘记导入from django.shortcuts import render

链接到文档:https://docs.djangoproject.com/en/2.0/topics/forms/#the-view