在我的应用程序中,我需要在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'),
如何在不出现上述错误的情况下在每个页面上显示此表单?
答案 0 :(得分:0)
所以,我选择了不同的方法,我最终得到了这个解决方案:
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'),
基本上,表单操作会将我重定向到视图功能,它会执行我必须执行的操作,它会将我重定向回同一页面。