django + uwsgi + ngnix = Django CSRF验证错误

时间:2013-06-26 10:50:08

标签: django

我有一个简单的应用程序,允许您将图像上传到服务器上,并在我的生产服务器上设置,该服务器由django + uwsgi + ngnix组成。现在的问题是csrf令牌没有出现在模板中,当我尝试上传图片时显示此错误

Forbidden (403)

CSRF verification failed. Request aborted.
Reason given for failure:
CSRF token missing or incorrect.

我清楚地理解这个错误。 {% csrf_token %}位于模板内,并且MIDDLEWARE_CLASSES上启用了csrf。我还在开发服务器上测试了我的应用程序,它运行正常。什么可能导致{% csrf_token %}不出现在我的生产服务器上的模板中。

我可以看到表单,但是当我查看源代码时,没有csrf令牌。

设置

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '/home/projects/mysite/d.db',                      # Or path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        'USER': '',
        'PASSWORD': '',
        'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        'PORT': '',                      # Set to empty string for default.
    }
}


ALLOWED_HOSTS = []


TIME_ZONE = 'America/Chicago'

LANGUAGE_CODE = 'en-us'

SITE_ID = 1


U    SE_I18N = True


USE_L10N = True

USE_TZ = True

MEDIA_ROOT = '/home/projects/mysite/media/'


MEDIA_URL = '/media/'


STATIC_ROOT = ''

STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

ist of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#         'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'mysite.urls'


# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'mysite.wsgi.application'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

视图

def upload(request):
    form = ImageForm()
    if request.POST:
        form = ImageForm(request.POST, request.FILES)

        image = request.FILES.get('image')
        CarPhoto.objects.create(user=request.user,cars=1,description='dwq',image=image)
    return render(request,'image.html',{'form':form})

模板

<form method="POST" enctype="multipart/form-data">

{% csrf_token %}
<div id="c">image</div> {{form.image}}
dwqdwqdwq
        <input type = "submit" value= "add" id="box2"/>
</form>{% csrf_token %}

查看来源

 <form method="POST" enctype="multipart/form-data"><div id="c">image</div><input    id="id_image" name="image" type="file" /> dwqdwqdwq <input type="submit" value="add" id="box2"/></form>

1 个答案:

答案 0 :(得分:3)

您的视图缺少令牌,因为您没有设置它。

更改此行

return render(request,'image.html',{'form':form})

context = {'form':form,}
context.update(csrf(request))
return render(request,'image.html', context)

from django.core.context_processors import csrf
from django.shortcuts import render_to_response

return render_to_response('image.html', context, context_instance=RequestContext(request))

您可以根据自己的喜好使用,也可以使用模板中的{% csrf_token %}<form>之外的那个是多余的。

Reading the docs is good!