在一个模板中区分创建和更新表单 [英] Within a template distinguish between create and update form
问题描述
如果CreateView和UpdateView正在使用相同的模板model_form.html,那么在模板中,如果我正在创建或更新表单,我将如何区分?
If the CreateView and UpdateView are using the same template "model_form.html" then within the template how would I differentiate if I am creating or updating a form?
我的通用视图如下
class AuthorCreateView(CreateView):
form_class = AuthorForm
model = Author
class AuthorUpdateView(UpdateView):
form_class = AuthorForm
model = Author
AuthorForm如下
AuthorForm is as follows
class AuthorForm(ModelForm):
class Meta:
model = Author
fields = ('first_name', 'last_name')
我的模板如下
<form action="" method="post">
{% csrf_token %}
<table border="0" cellpadding="4" cellspacing="0">
<tr>
<td>First Name</td>
<td>{{ form.first_name.errors }}{{ form.first_name }}</td>
</tr>
<tr>
<td>Last Name</td>
<td>{{ form.last_name.errors }} {{ form.last_name }}</td>
</tr>
</table>
{% if form.isNew %}
<input type="submit" value="Update Author" />
{% else %}
<input type="submit" value="Add Author" />
{% endif %}
</form>
在我的模板中,我想区分创建和更新视图?
In my template I would like to differentiate between create and update view?
推荐答案
在更新视图中,会有一个 form.instance
,而 form.instance.pk
不会为None。在创建视图中,可能有也可能不是 form.instance
,但即使有 form.instance.pk
将为无。
In an update view, there'll be a form.instance
, and form.instance.pk
will not be None. In a create view, there may or may not be form.instance
, but even if there is form.instance.pk
will be None.
这篇关于在一个模板中区分创建和更新表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!