如何在Django中初始化我的表单?

时间:2017-10-15 11:14:23

标签: django forms django-forms

我已在我的主页上创建了一个联系表单,但在我第一次点击提交表单之前,该表单没有显示。即调用get方法。我想将其作为单独的视图保存到我的主页,以便在重新点击“提交”时它对我的主页没有影响。有没有办法加载我的def电子邮件'当我的主页加载?

模板表单

<form method="post" action="{% url 'home_page:email' %}">
            {% csrf_token %}
{#            {% bootstrap_form form.as_p %}#}
            {{ form.as_p }}
            <input type="submit" value="Sign Up" class="btn btn-default">
        </form>

网址

urlpatterns = [
    url(r"^$", views.HomePage.as_view(), name="home"),
    url(r'^email/$', views.email, name='email'),
    url(r'^success/$', views.success, name='success'),
]

视图

class HomePage(MessageMixin, TemplateView):
    template_name = "index.html"

def email(request):
    if request.method == 'GET':
        form = ContactForm()
    else:
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            from_email = form.cleaned_data['from_email']
            message = form.cleaned_data['message']
            try:
                send_mail(subject, message, from_email, ['admin@example.com'])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('success')
    return render(request, "index.html", {'form': form})

1 个答案:

答案 0 :(得分:1)

将表单包含在 HomePage 视图上下文中。像这样:

class HomePage(MessageMixin, TemplateView):
    template_name = "index.html"

    def get_context_data(self, **kwargs):
         context = super(HomePage, self).get_context_data(**kwargs)
         context['form'] = ContactForm(None)
         return context