1

我有一个带有 ImageField 表单的 django 模板,允许用户在网站上上传图片。

1) 表单包含 {% csfr_token %} 2) 我用渲染变量渲染模板。

另外,我在模板的表单中设置了 enctype="multipart/form-data" 吗?

我仍然得到一个CSFR验证。失败。任何人都可以帮忙吗?

来自 template.html 的代码

<form enctype="multipart/form-data" action='{% url photo username %}' method="post">
            {% csrf_token %}
              <p>{{ form.non_field_errors }}</p>
              <p>{{ form.profile_picture.label_tag }} {{ form.profile_picture.help_text }}</p>
              <p>
              {{ form.profile_picture.errors }}
              {{ form.profile_picture }}
              </p>
              <p><input type="submit" value="Upload" /></p>
            </form>   

风景:

def upload_photo(request, nick):
#c = {}
#c.update(csrf(request))
if request.method == 'POST':
    form = PictureForm(request.POST, request.FILES)
    if form.is_valid():
        newpic = Picture(profile_picture = request.FILES['profile_picture'])
        newpic.save()

        # Redirect to the document list after POST
        return HttpResponseRedirect(reverse('profiles.views.upload_photo', args=[nick]))
else:
    form = PictureForm() # A empty, unbound form

# Load documents for the list page
pictures = Picture.objects.all()

# Render list page with the documents and the form
return render_to_response(
    'profile.html',
             #various render variables here
             })

更新:追溯

Environment:


Request Method: POST
Request URL: localhost/hello/john/

Django Version: 1.4.2
Python Version: 2.7.2
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django.contrib.admindocs',
 'friendship',
 'search',
 'tour',
 'profiles')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/mike/Documents/ics/django/ics/profiles/views.py" in upload_photo
  18.           newpic.save()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save
  463.         self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save_base
  551.                 result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in _insert
  203.         return insert_query(self.model, objs, fields, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in insert_query
  1593.     return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py" in execute_sql
  909.         for sql, params in self.as_sql():
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py" in as_sql
  872.                 for obj in self.query.objs
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/files.py" in pre_save
  249.             file.save(file.name, file, save=False)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/files.py" in save
  85.         name = self.field.generate_filename(self.instance, name)
File "/home/mike/Documents/ics/django/ics/profiles/models.py" in get_image_name
  8.    name =  str(instance.user_id) + ".jpg"
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py" in __get__
  343.                 raise self.field.rel.to.DoesNotExist

我发现错误在这里(models.py):

def get_image_name(instance, filename):
    return  str(instance.user_id) + ".jpg"
    #str(____) + ".jpg" causes the exception

class Picture(models.Model):
    user_id = models.ForeignKey(User)
    profile_picture = models.ImageField(storage=OverwriteStorage(), upload_to=get_image_name)

任何想法为什么会发生这种情况?

我想要做的是保存用户上传的图片和他们的用户名。但是如何在models.py 中获取用户的用户名?

4

1 回答 1

1

由于您没有使用 csrf 令牌手动更新上下文,因此您必须在渲染到响应方法中使用 RequestContext

return render_to_response('profile.html', { 
   ..your data dict.. }, context_instance=RequestContext(request))

请参阅https://docs.djangoproject.com/en/1.2/ref/templates/api/#subclassing-context-requestcontext(我链接到旧版本的 django,因为您仍然使用函数样式视图)

编辑:

现在 csrf 问题已解决,您正在处理一个单独的新错误。尝试在您的图片模型中将“user_id”更改为“用户”(以保持一致性)并str(instance.user.username)在您的 get_image_name 中使用。即使这不起作用(它通常应该),请在原始请求已得到回答时发布一个新问题。人们可以搜索 csrf 并在这里结束,阅读一个不相关的问题。

于 2012-12-27T03:36:20.603 回答