python - 如果表单在我的基本模板文件中,如何实现表单提交?
问题描述
我有一个基本模板文件,其中包含用户订阅电子邮件通讯的表单。我的所有模板都继承自基本模板文件,因为我想在每个网页上显示此表单。
我不知道如何使表单将用户输入的数据提交到数据库中。到目前为止,我处理了视图,并且每个视图都特定于一个 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"])
我如何实现我想要的?
解决方案
您需要使用,它会在调用方法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/
推荐阅读
- react-native - React Native 远程 JSON 配置文件 react native
- bokeh - 我可以在 Bokeh HoverTool 文本中添加一个很酷的 Unicode 上/下三角形吗?
- html - 我该如何停止
- 重叠的元素
- python - 如何在 GeoPandas 的图例中显示两个颜色图
- r - 如何在分组数据框中创建一列百分比?
- postgresql - Auth Middleware 仅适用于一条快速路由
- php - 在“选择选项”按钮上显示一个弹出窗口 - Woocommere
- reactjs - 为什么我必须单击 TextField 两次才能显示我的列表?
- pyspark - PySpark 将索引列传递给 element_at()
- c++ - 模板如何避免无限递归?