【问题标题】:How do I implement a form submission if the form is in my base template file?如果表单在我的基本模板文件中,如何实现表单提交?
【发布时间】:2021-02-14 22:54:24
【问题描述】:

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

我不知道如何让表单将用户输入的数据提交到数据库中。 到目前为止,我处理的是视图,每个视图都特定于一个 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"])

如何实现我想要的?

【问题讨论】:

    标签: python django django-views django-forms django-templates


    【解决方案1】:

    您需要使用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/

    【讨论】:

    • 我有两个问题:1)我如何将视图链接到表单(因为表单在我的网站上无处不在并且没有特定的 URL)? 2) 为什么我不应该使用modelform_factory?为什么要从 ModelForm 继承呢?
    • 也许您可以创建一个中间件,负责检查您是否提交了此表单并处理数据,然后再返回当前页面
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多