当我尝试使用表单上传用户个人资料图片时,允许用户编辑他们的帐户信息 - 没有任何事情发生。
我不知道该怎么做才能让这个上传工作。
models.py :
class UserProfile(models.Model):
objects = models.Manager()
user = models.OneToOneField(User)
image = models.ImageField(upload_to='profile_image', blank=True)
def __str__(self):
return self.user.username
forms.py :
class EditProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = (
'image',
)
views.py :
def edit_profile(request):
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user.userprofile)
if form.is_valid():
form.save()
return redirect(reverse('accounts:view_profile'))
else:
form = EditProfileForm(instance=request.user.userprofile)
args = {'form': form}
return render(request, 'accounts/edit_profile.html', args)
settings.py :
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mainapp/media')
修改-profile.html :
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
答案 0 :(得分:0)
如果您想将文件(包括图片)上传到Django View,您应该从request.FILES
获取文件。像这样:
if request.method == 'POST':
form = EditProfileForm(request.POST, request.FILES, instance=request.user.userprofile)
if form.is_valid():
data = form.save(commit=False)
data.user = request.user
data.save()
return redirect(reverse('accounts:view_profile'))