Django中无法上传图片

5
我有一个个人资料页面,我想让用户上传个人资料图片。我可以编辑所有的文本,但无法上传图像。如果我通过管理员添加图片,它可以工作,但是不能通过用户在网站上的个人资料页面添加。请注意,当通过管理员创建时,它会正确地上传到我在媒体文件夹中指定的目录(profile_image)。我在模板页面上创建了一些错误处理,但生成的错误是:“'image'属性没有与之关联的文件。”以下是我的代码:
models.py
class UserProfile(models.Model):
    user = models.OneToOneField(User)
    first_name = models.CharField(default='',max_length=100 )
    last_name = models.CharField(default='',max_length=100)
    email = models.CharField(max_length=100, default='')
    date_birth = models.DateField(default=datetime.datetime.now())
    bio = models.TextField(default='')
    image = models.ImageField(upload_to='profile_image', blank=True)


def create_profile(sender, **kwargs):
    if kwargs['created']:
        user_profile = UserProfile.objects.create(user=kwargs['instance'])

post_save.connect(create_profile, sender=User)

views.py

@login_required
def edit_profile(request):
    profile = get_object_or_404(models.UserProfile)
    if request.method == 'POST':
        form = forms.EditProfileForm(data=request.POST, instance=profile)

        if form.is_valid():
            form.save()
            return redirect('/accounts/profile')
    else:
        form = forms.EditProfileForm(instance=profile)
        args = {'form':form}
        return render(request, 'accounts/edit_profile.html', args)

forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm

from . import models


class UserProfileForm(forms.ModelForm):
    class Meta:
        model = models.UserProfile
        fields = [
            'first_name',
            'last_name',
            'email',
            'date_birth',
            'bio',
            'image',
        ]


class EditProfileForm(UserProfileForm):
    model = models.UserProfile
    fields = [
        'first_name',
        'last_name',
        'email',
        'date_birth',
        'bio',
        'image',
    ]

settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'accounts/media')

edit_profile.html

{% extends "layout.html" %}

{% block title %}User Profile | {{ user }}{{ super }}{% endblock %}

{% block body %}
<h1>My Profile</h1>

<form action="" method="POST" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p}}
    <button type="submit">Save</button>
</form>

{% endblock %}
2个回答

10
文件在视图中使用 request.FILES 而不是 request.POST。请按照以下步骤进行操作:
form = forms.EditProfileForm(data=request.POST, files=request.FILES, instance=profile)

请查看文件上传的文档

处理此表单的视图将在request.FILES中接收文件数据,该字典包含表单中每个FileField(或ImageField或其他FileField子类)的键。


好的,就这样。非常感谢您的帮助。 - John Rogerson
4
在模板中相应的<form>标签中绝不要忘记添加“enctype='multipart/form-data'”,否则,如果仍然存在问题,您会一直苦思冥想,直到头发都秃光为止。 - R.R.C.

0
请检查您的文件夹权限,DRF 对我来说没有抛出任何权限错误。
对于 Mac,请使用:sudo chmod 777 * 对于 Live Server,请不要使用此方法,只需检查与您的操作系统相关且安全的内容即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接