CSRF令牌丢失或不正确。 Django 1.8餐厅应用

时间:2015-09-16 01:45:17

标签: python django

我收到此错误(在Chrome上):

CSRF token missing or incorrect

我想做的是做一个餐馆申请。我有我的菜单项,我正在尝试在订单表中创建一条记录。只要单击一个按钮,我就想将该条目添加到订单表

以下是我的文件:

views.py

from django.shortcuts import render, render_to_response
from django.http import HttpRequest, HttpResponseRedirect
from django.template import RequestContext
from datetime import datetime
from app.models import *

def menu(request):
    menus = Menu.objects.all()
    return render_to_response('app/menu.html', {'menus':menus})

def menudetails(request,id):
    menu = Menu.objects.get(pk = id)
    return render_to_response('app/menudetails.html', {'menu':menu})

def myorders(request,id):
   # if request.method == "POST":
        #order = Order.createorder(Menu(pk=id))
       # order.save()
    if request.method == "GET":
        form = OrderForm()
        return render(request, 'app/menudetails.html',{ 'form':form })
    elif request.method == "POST":
        form = OrderForm(request.POST)
        form.save()
        return HttpResponseRedirect('/menu');


def addmenu(request):
    if request.method == "GET":
        form = MenuForm()
        return render(request, 'app/addmenu.html',{ 'form':form })
    elif request.method == "POST":
        form = MenuForm(request.POST)
        form.save()
        return HttpResponseRedirect('/menu');

def home(request):
    """Renders the home page."""
    assert isinstance(request, HttpRequest)
    return render(
        request,
        'app/index.html',
        context_instance = RequestContext(request,
        {
            'title':'Home Page',
            'year':datetime.now().year,
        })
    )

def contact(request):
    """Renders the contact page."""
    assert isinstance(request, HttpRequest)
    return render(
        request,
        'app/contact.html',
        context_instance = RequestContext(request,
        {
            'title':'Contact',
            'message':'Your contact page.',
            'year':datetime.now().year,
        })
    )

def about(request):
    """Renders the about page."""
    assert isinstance(request, HttpRequest)
    return render(
        request,
        'app/about.html',
        context_instance = RequestContext(request,
        {
            'title':'About',
            'message':'Your application description page.',
            'year':datetime.now().year,
        })
    )

urls.py

from datetime import datetime
from django.conf.urls import patterns, url
from app.forms import BootstrapAuthenticationForm

# Uncomment the next lines to enable the admin:
# from django.conf.urls import include
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    #url(r'^myorders$', 'app.views.myorders', name = 'myorders'),
    url(r'^menu$', 'app.views.menu', name = 'menu'),
    url(r'^addmenu$', 'app.views.addmenu', name = 'addmenu'),
    url(r'^menu/(?P<id>\d+)$', 'app.views.menudetails', name = 'menudetails'),
    url(r'^menu/(?P<id>\d+)/order$', 'app.views.myorders', name = 'myorders'),
    url(r'^$', 'app.views.home', name='home'),
    url(r'^contact$', 'app.views.contact', name='contact'),
    url(r'^about', 'app.views.about', name='about'),
    url(r'^login/$',
        'django.contrib.auth.views.login',
        {
            'template_name': 'app/login.html',
            'authentication_form': BootstrapAuthenticationForm,
            'extra_context':
            {
                'title':'Log in',
                'year':datetime.now().year,
            }
        },
        name='login'),
    url(r'^logout$',
        'django.contrib.auth.views.logout',
        {
            'next_page': '/',
        },
        name='logout'),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
)

models.py

from django.db import models
from django import forms
from datetime import datetime

class Menu(models.Model):
    name = models.CharField("Menu Item", max_length = 50)
    desc = models.CharField("Description", max_length = 100)
    price = models.DecimalField(max_digits=6, decimal_places = 2)

class MenuForm(forms.ModelForm):
    class Meta:
        model = Menu;
        fields = ['name','desc','price'];

class Order(models.Model):
    menuItem = models.ForeignKey(Menu)
    ordercreated = models.DateTimeField(auto_now_add = True)
    orderupdate = models.DateTimeField(auto_now = True)
    completed = models.BooleanField(default = False)
    user = models.CharField(max_length = 30, blank = True)

    def createorder(cls, menu):
        order = cls(menuItem = menu)
        return order

1 个答案:

答案 0 :(得分:0)

如何避免此错误,解决方案如下:

  1. 在模板中添加{% csrf_token %}
  2. 链接:csrf_token

    1. 在您的视图中添加@csrf_exempt
    2. 链接:csrf_exempt