我有一个包含像这样的ImageField的模型:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['photo',]
和表格如:
def show_form(request):
form = MyModelForm(request.POST or None)
content = {
'form': form,
}
if form.is_valid():
mymodel = form.save(commit=False)
mymodel.save()
return render(request, 'appname/template.html', content)
和我认为:
<!DOCTYPE html>
<html>
<body>
<form action="" method="POST">
{% csrf_token %}
<table align="center">
{{ form.as_table }}
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
</body>
</html>
和我的模板:
ApplicationContext
但每当我选择一张图片并点击提交时,表单都会告诉我该字段是必填字段并且不保存。
提前致谢。
答案 0 :(得分:1)
您需要在upload_to
ImageField
参数
photo = models.ImageField(upload_to='images')
并制作这样的表格
<form action="" method="POST" enctype="multipart/form-data">
并确保您已定义MEDIA_URL
和MEDIA_ROOT
并将您的观点更改为此
def show_form(request):
if request.method == 'POST':
form = MyModelForm(request.POST or None)
if form.is_valid():
mymodel = form.save(commit=False)
mymodel.save()
else:
content = {
'form': form,
}
return render(request, 'appname/template.html', content)