Django图像上传 [英] Django image uploading

查看:80
本文介绍了Django图像上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在上传图片时遇到问题.目前,所选的图像文件尚未复制到目标目录,并且该文件的路径也未添加到数据库.

I have a problem with image uploading. For now, chosen image file is not copied to destination directory and path to this file is not added to database.

我在下面提供我的代码:

I'm giving my code below:

models.py:

models.py:

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    avatar = models.ImageField(upload_to="avatar/")

form.py

class ProfileEditionForm(ModelForm):
    class Meta:
        model = UserProfile
        exclude = ('user')

view.py:

def index(request):
    if request.user.is_authenticated():
        user = User.objects.get(pk=request.user.id)

        if request.method == "POST":
            form = ProfileEditionForm(request.POST, request.FILES, instance=user)

            if form.is_valid():
                form.save()
                #return HttpResponseRedirect(reverse('profile_edit'))
        else:
            form = ProfileEditionForm(instance=user)

        return direct_to_template(request, 'profile_edit.html', { 'form' : form })
    else:
        return HttpResponseRedirect(reverse('main_page'))

预先感谢您的帮助.

推荐答案

您的ModelForm已绑定到UserProfile模型,但是您正在使用instance = user实例化它.

your ModelForm is bound to UserProfile model, but your are instantiating it with instance=user.

PS:request.user是User.objects.get(pk = request.user.id)

PS: request.user is User.objects.get(pk=request.user.id)

这篇关于Django图像上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆