我可以上传个人资料图片,但我无法编辑
我有填充图像浏览选项的表单,但是当我单击“保存”时,它实际上并未在模板中更新。但它在管理中工作正常
views.py
def create_form(request):
form = AlbumForm(request.POST or None, request.FILES or None)
if form.is_valid():
album = form.save(commit=False)
album.user = request.user
album.image= request.FILES['image']
album.save()
return render(request, 'about.html', {'album': album})
context = {
"form": form,
}
return render(request, 'create_form.html', context)
def profile_edit(request):
if request.method == 'POST':
form = AlbumForm(request.POST, instance=request.user.album)
if form.is_valid():
album = form.save(commit=False)
album.user = request.user
form.save()
return redirect(reverse('about'))
else:
form = AlbumForm(instance=request.user.album)
args = {'form': form}
return render(request, 'profile_edit.html', args)
models.py
class Album(models.Model):
user = models.OneToOneField(User)
image = models.FileField()
forms.py
class AlbumForm(forms.ModelForm):
class Meta:
model = Album
fields = ['image']
profile_edit.html
{% extends 'base.html' %}
{% block content %}
<form action="{% url 'profile_edit' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">save</button>
</form>
<div>
<img src="{{ user.album.image.url }}" class="img-responsive">
</div>
{% endblock %}
答案 0 :(得分:1)
试试这个
AlbumForm(request.POST, request.FILES, instance=request.user.album)
答案 1 :(得分:0)
您需要在个人资料编辑视图中将request.FILES
添加到AlbumForm
。
答案 2 :(得分:0)
如果您上传文件,则必须使用request.Files
阅读更多信息此链接
https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/#basic-file-uploads