首页 > 解决方案 > 如果表单在我的基本模板文件中,如何实现表单提交?

问题描述

我有一个基本模板文件,其中包含用户订阅电子邮件通讯的表单。我的所有模板都继承自基本模板文件,因为我想在每个网页上显示此表单。

我不知道如何使表单将用户输入的数据提交到数据库中。到目前为止,我处理了视图,并且每个视图都特定于一个 URL,所以对于我来说如何对所有 URL 执行此操作并不是很明显,因为所有 URL 上都存在基本模板。

base.html(基本模板文件):

{% load static %}
<html>
<head>
   <title>{% block title %}{% endblock %}</title>
</head>
<body>
   <a href="{% url 'employers:list_joblistings' %}"> Homepage </a>
   <a href="{% url 'employers:submit_job_listing' %}"> Post a job </a>
   {% block content %}{% endblock %}
   <p> Subscribe to new jobs: </p>
   <form method="post">
       <p> Email: <input type="email" name="email" /> </p>
       <p> First name: <input type="text" name="first_name" /> </p>
       <p> Last name: <input type="text" name="last_name" /> </p>
       <input type="submit" value= "Submit">
   </form>
</body>
</html>

我还在我的forms.py文件中制作了一个表单,该表单从我的电子邮件订阅者模型中构造了表单,但到目前为止我还没有在任何地方使用它:

EmailSubscriberForm = modelform_factory(EmailSubscriber, fields=["email", "first_name", "last_name"])

我如何实现我想要的?

标签: pythondjangodjango-viewsdjango-formsdjango-templates

解决方案


您需要使用,它会在调用方法ModelForm时将表单链接到模型。save()(这也会增加很多安全性)

from django.forms import ModelForm
from myapp.models import EmailSubscriber

# Create the form class.
class EmailSubscriberForm(ModelForm):
    # if email is an EmailField, `is_valid` method will check if it's an email
    class Meta:
        model = EmailSubscriber
        fields = ["email", "first_name", "last_name"]

然后在视图中,您可以创建并作为上下文传递或获取响应并保存到数据库

if request.method == "POST":
    form = EmailSubscriberForm(request.POST)
    if form.is_valid():
        email_subscriber = form.save()
    # generally call `return HttpResponseRedirect` here
else:
    form = EmailSubscriberForm()
    # generally call `return render(request, 'page.html', {'form': form})

你只需在你的模板中调用它:

<form method="post">
    {{ form }}
</form>

参考:https ://docs.djangoproject.com/en/3.1/topics/forms/modelforms/


推荐阅读