【发布时间】: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', '/'),所以我可以在发布后将他重定向到同一页面