要在我的一个CreatView类中包装一些文本,我使用HTML模板包装表单。但是,使用此模板时,所有内容均按预期工作,但不保存传递到表单的ImageField的图像。注释掉设置CreateView模板的行即可解决此问题。但是我想使用模板来选择在页面上显示更多信息,而不仅仅是表单。 将表单包装到模板中时,表单的逻辑如何改变?
views.py
class PieceInstanceCreate(LoginRequiredMixin, CreateView):
model = PieceInstance
fields = ['version', 'piece_image', 'status']
# commenting out the below line makes the form save the image
template_name = 'pieceinstance_create.html'
def form_valid(self, form):
form.instance.piece = Piece.objects.get(id=self.kwargs['pk'])
return super(PieceInstanceCreate, self).form_valid(form)
def get_success_url(self):
return reverse_lazy('piece-detail', kwargs={'pk': self.kwargs['pk']})
pieceinstance_create.html
{% extends "base_generic.html" %}
{% block content %}
<h1>Add a Version</h1>
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
{% endblock %}
答案 0 :(得分:3)
在模板中,您需要设置表单属性enctype =“ multipart / form-data”:
<form action="" method="post" enctype="multipart/form-data">