html - Django - 如何在页脚中使用表单
问题描述
以前,我在主页 (index.html) 上有我的“订阅时事通讯”表单。但是,我将其移至 footer.html 以便在每个页面上显示。
问题是由于处理表单的逻辑只在主页视图中,提交到表单只能在主页上工作。
这里有一些代码可以帮助你理解:
这在 footer.html 中,它包含在 base.html 中,由所有其他 html 扩展
<form class="nwsltr-primary-1" action="." method="POST"> <!-- . means current URL we are on -->
{% csrf_token %}
<input type="email" name="email" id="email" placeholder="Your email"/>
<button type="submit"><i class="ion-ios-paperplane"></i></button>
</form>
这是我认为需要改变的。这是主页的视图,也是唯一可以看到表单逻辑的地方:
def index(request):
# featured and object_list get all Posts with featured bool true. order_by=latest first. :6=first 6
featured = Post.objects.filter(featured=True).order_by('-share_count')[:6]
latest = Post.objects.order_by('-timestamp')[:5]
popular = Post.objects.order_by("-share_count")[:4]
# Basic but does not do any verification
if request.method == "POST":
email = request.POST["email"]
new_signup = Signup()
new_signup.email = email
new_signup.save()
context = {
'object_list': featured,
'latest': latest,
'popular': popular
}
return render(request, 'index.html', context) # html page that will be shown
如何使上面的 if 语句可以在每个页面上运行,而无需将其复制到每个视图?
解决方案
我有两个想法如何解决这个问题:
您可以将表单的逻辑放在一个额外的函数中,并在您需要的每个视图函数中调用此函数
您可以使用基于类的视图并创建一个包含表单逻辑的“通用超类”。之后所有的“子类”都从超类继承。这是一个带有示例的链接:通用超类
推荐阅读
- node.js - Hyperledger Fabric 中不区分大小写的正则表达式
- c# - 无法加载文件或程序集“Microsoft.SqlServer.Management.RegisteredServers,版本=15.2.0.0,文化=中性,PublicKeyToken=89845dcd8080cc91”
- java - OOP - 实例和对象之间的正确定义是什么?
- cypress - 用赛普拉斯存根响应
- iphone - 仅在特定设备上安装 iOS ipa
- laravel - Laravel 尝试排队作业,触发新尝试的正确方法?
- java - 如何使用 Rest Assured-Java 为 JSON 正文中的参数赋值
- c# - 线程完成后捕获异常
- javascript - 如何计算代码镜像中未保存的更改
- spring - 使用 spring kafka 中的注释为每个主题单独的 Kafka 侦听器