【问题标题】:Django add form on every pageDjango 在每个页面上添加表单
【发布时间】:2018-07-18 19:52:47
【问题描述】:

在我的应用程序中,我需要在 base.html 中添加一个表单,我已经完成了。为此,我使用了 context_processors,现在我的问题是每次我尝试发布时,我都会得到一个空白页并且这个错误:Method Not Allowed (POST)

在这个表单中,我只想添加一个按钮,它将所有当前用户通知标记为已读。

我知道你可以像这样使用 context_processors:

def my_context(request):
    data = dict()
    if request.user.is_authenticated:
        data['notifications'] = Notification.objects.filter(user=request.user, read=False)
        data['form'] = NotificationForm()
        return data

但是我需要这些行而不是添加表单:

def my_context(request):
    data = dict()
    if request.user.is_authenticated:
        data['notifications'] = Notification.objects.filter(user=request.user, read=False)
    if request.method == 'POST':
        if 'read-notifications' in request.POST:
            for notification in data['notifications']:
                notification.read = True
                notification.save()
        next = request.POST.get('next', '/')
        return redirect(next)
    return data

base.html中的表单:

<form action="" method="POST">{% csrf_token %}
    <input type="hidden" name="next" value="{{ request.path }}">
    <button type="submit" class="btn m-btn--square  btn-primary" name="read-notifications">Mark as read</button>
</form>

urls.py

url(r'^orders/create/$', views.admin_order_document, name='create_order'),
url(r'^orders/waiting/$', views.OrdersWaitingListView.as_view(), name='order_waiting_list'),
url(r'^orders/unallocated/$', views.OrdersUnallocatedListView.as_view(), name='order_unallocated_list'),
url(r'^orders/working/$', views.OrdersWorkingListView.as_view(), name='order_working_list'),

如何在每个页面上显示此表单而不会出现上述错误?

【问题讨论】:

  • {% csrf_token %} 真的在那里渲染了吗?
  • 显示您的网址。可能是这样的问题stackoverflow.com/questions/42464834/…
  • 是的,当然,但我怀疑
  • 我在您的网址中看不到 my_context 视图。
  • 因为我没有在那里使用它,所以我使用了next = request.POST.get('next', '/'),所以我可以在发布后将他重定向到同一页面

标签: django forms


【解决方案1】:

所以,我选择了一种不同的方法,最终得到了这个解决方案:

base.html

<form action="{% url 'mark_read' %}" method="POST">{% csrf_token %}
    <input type="hidden" name="next" value="{{ request.path }}">
    <button type="submit" class="btn m-btn--square  btn-primary" name="action" value="mark_read">Marchează ca citite</button>
</form>

views.py

@login_required()
def read_notifications(request):
    if request.method == 'POST':
        if 'action' in request.POST:
            notifications = Notification.objects.filter(user=request.user, read=False)
            for notification in notifications:
                notification.read = True
                notification.save()
        next = request.POST.get('next', '/')
        return redirect(next)

urls.py

url(r'^mark-read/$', views.read_notifications, name='mark_read'),

基本上,表单操作会将我重定向到视图功能,它会做我必须做的事情并将我重定向回同一页面。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-13
    • 2017-01-21
    • 2023-03-12
    • 2021-07-28
    • 1970-01-01
    • 2015-01-30
    • 2013-02-16
    • 1970-01-01
    相关资源
    最近更新 更多