Django图片上传问题

时间:2017-06-29 09:14:27

标签: django

我试图上传图片。这是用户个人资料的头像图片。

目前,表单没有返回错误,但我的数据库或我的文件夹media / avatar /中没有写任何内容。

出了什么问题?

我的观点:

def view_avatar(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES, instance=request.user.profile)
        if form.is_valid():
            form.save()            
    else:
        form = UploadFileForm(instance=request.user.profile)
    return render(request, 'avatar.html', locals())

我的表格:

class UploadFileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('avatar',)

我的模特:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    birthdate = models.DateField(null=True, blank=True)
    avatar = models.ImageField(upload_to='media/avatar/', blank=True, null=True)

4 个答案:

答案 0 :(得分:1)

这是因为您使用的表单是从forms.Form继承的,您需要使用forms.ModelForm直接保存实例。

更改此行,

class UploadFileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('avatar', )

    def save(self, *args, **kwargs):
        profile, created = Profile.objects.get_or_create(user=self.user)
        profile.avatar = self.cleaned_data['avatar']
        profile.save()
        return profile

另外,在这样的视图中进行编辑,

if form.is_valid():
    file = form.save(commit=False)
    file.user = request.user
    file.save()

答案 1 :(得分:1)

制作个人资料时,您可以使用信号。

这样,无论何时添加新用户,都会自动为该用户生成配置文件

您的models.py

from django.conf import settings
from django.db.models.signals import post_save


class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)
    birthdate = models.DateField(null=True, blank=True)
    avatar = models.ImageField(upload_to='media/avatar/%y/%m/%d', blank=True, null=True)


def post_save_profile(sender, instance, created, *args, **kwargs):
    if created:
        try:
            Profile.objects.create(user=instance)
        except:
            pass

post_save.connect(post_save_profile, sender=settings.AUTH_USER_MODEL)

并且为了更新生日和头像等信息,您可以使用ModelForm。

forms.py

class UploadFileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('birthdate', 'avatar')

    def __init__(self, *args, **kwargs):
        super(UploadFileForm, self).__init__(*args, **kwargs)
        self.fields['avatar'].required = False

您的views.py

def view_avatar(request):
    user = request.user
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES, instance=user.profile)
            if form.is_valid():
                form.save()

对于模板中的头像,您可以使用:

<img src="{% if user.profile.avatar %}{{ user.profile.avatar.url }}{% else %}{% static 'no-avatar.jpg' %}{% endif %}"><i></i>

答案 2 :(得分:0)

您可以为此编写自定义保存方法。

查看:

def view_avatar(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES, user=request.user)
        if form.is_valid():
            form.save()

    else:
        form = UploadFileForm()
    return render(request, 'avatar.html', locals())

<强>形式:

class UploadFileForm(forms.Form):
    class Meta:
        model = Profile
        fields = ('avatar', )

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(UploadFileForm, self).__init__(*args, **kwargs)
        self.fields['avatar'].required = False

    avatar = forms.FileField()


    def save(self, *args, **kwargs):
        user_profile, created = Profile.objects.get_or_create(user=self.user)
        user_profile.avatar = self.cleaned_data.get('avatar')
        user_profile.save()
        return user_profile

答案 3 :(得分:0)

我忘记了enctype! 解决方案是:

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