无法在django上传个人资料图片

时间:2015-01-09 10:03:20

标签: python django

我正在尝试为Django用户上传个人资料图片,但它不起作用,其他字段(网站)工作得很好。我尝试了几种解决方案,但我找不到任何对我有用的解决方案。我不知道出了什么问题,我只是Django的新手。我希望你能帮助我。

models.py

    class UserProfile(models.Model):
        user = models.OneToOneField(User)
        website = models.URLField(blank=True)
        picture = models.ImageField(upload_to='profile_images', blank=True)

        def __unicode__(self):
            return self.user.username

    User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])

views.py

    @login_required
    def edit_profile(request):
        context = RequestContext(request)
        if request.method == "POST":
            form = UserProfileForm(request.POST,request.FILES, instance=request.user.profile)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('/rango/profile/')
        else:
            user = request.user
            profile = user.profile
            form = UserProfileForm(instance=profile)

        return render_to_response('rango/profile_registration.html', {'form':form}, context)

3 个答案:

答案 0 :(得分:1)

确保您已在设置中设置了MEDIA_ROOT,如下所示

import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'

还要确保首先创建了MEDIA_ROOT目录。希望它有所帮助。

答案 1 :(得分:0)

您是否在Django项目的根路径中创建了一个“media”文件夹?

以下是有关Django中静态文件的一些信息:Django-static-files

在我的一个项目中,我在settings.py中有以下条目

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, "media")

我还在项目根目录中创建了两个foldes。

否则,如果这不起作用,请提供有关错误日志的更多信息。

答案 2 :(得分:0)

在您希望用户上传图片的表单中加入enctype="multipart/form-data"



<form class=""  method="post" enctype="multipart/form-data">
  {% csrf_token %}
  {{form.as_table}}
  <input type="submit" name="" value="submit">
</form>
&#13;
&#13;
&#13;

我也有与你相同的要求,这有帮助。

相关问题