【问题标题】:Django - How To Use Form In FooterDjango - 如何在页脚中使用表单
【发布时间】:2019-12-06 18:55:07
【问题描述】:

以前,我在主页 (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 语句可以在每个页面上运行而无需将其复制到每个视图?

【问题讨论】:

  • 您是手动创建表单吗?

标签: html django forms django-views footer


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2017-09-27
    • 1970-01-01
    • 2015-08-09
    • 2018-10-27
    • 2011-07-23
    • 2014-10-17
    • 2012-04-29
    • 2021-11-19
    • 1970-01-01
    相关资源
    最近更新 更多