首页 > 解决方案 > 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 语句可以在每个页面上运行,而无需将其复制到每个视图?

标签: htmldjangoformsdjango-viewsfooter

解决方案


我有两个想法如何解决这个问题:

  1. 您可以将表单的逻辑放在一个额外的函数中,并在您需要的每个视图函数中调用此函数

  2. 您可以使用基于类的视图并创建一个包含表单逻辑的“通用超类”。之后所有的“子类”都从超类继承。这是一个带有示例的链接:通用超类


推荐阅读