这是我的表格。
class CreateBooksForm(forms.ModelForm):
languages = forms.CharField(widget=forms.TextInput)
file = forms.FileField(widget=forms.FileInput(attrs={'accept':'application/pdf'}))
class Meta:
model = Book
fields = "name","languages", "about","image","file"
这是我的视图。因此,当我渲染到更新视图模板时,我得到的语言和文件为空表单,而其他填充了。
@login_required
def post_update(request,pk):
update = get_object_or_404(Book,pk=pk)
form = CreateBooksForm(request.POST or None ,request.FILES or None,instance=update)
if request.method == 'POST':
if form.is_valid():
post = form.save(commit=False)
languages = form.cleaned_data['languages']
post.save() # must be save before adding m2m
tag_list=[Language.objects.get_or_create(name=tag)[0] for tag in post.languages.lower().split()]
for tag in tag_list:
a = post.language.add(tag)
post.language.set = a
post.save()
messages.success(request,'Updated successfully!')
update_book.delay(post.pk)
context ={
'form':form
}
return render(request,'books/update.html',context)
我的模板。这是我使用的简单的django酥脆模板。
<form method="POST" enctype="multipart/form-data">
<input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
<img class="rounded-circle" src="/media/{{form.image.value}}" height="100px" width="150px">
{{ form|crispy }}
<button type="submit" class="btn btn-dark">Update Books</button>
</form>
答案 0 :(得分:0)
您必须手动渲染每个字段以获取预填充的字段。 例如:
{% for field in form %}
{% if field.languages %}
<input type="name" id={{ field.languages.id_for_label }} value={{ field.languages.value }}/>
{% endif %}
{% endfor %}
有关更多详细信息,请参见docs