Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Within a template distinguish between create and update form

Tags:

django

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?

My generic view is as follows

class AuthorCreateView(CreateView):
    form_class = AuthorForm
    model = Author


class AuthorUpdateView(UpdateView):
    form_class = AuthorForm
    model = Author

AuthorForm is as follows

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('first_name', 'last_name')

My template is as follows

<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?

like image 844
iJK Avatar asked Sep 14 '13 21:09

iJK


2 Answers

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.

like image 140
Daniel Roseman Avatar answered Nov 15 '22 23:11

Daniel Roseman


From docs:

CreateView

object

When using CreateView you have access to self.object, which is the object being created. If the object hasn’t been created yet, the value will be None.

 

UpdateView

object

When using UpdateView you have access to self.object, which is the object being updated.

Solution:

{% if object %}
    <input type="submit" value="Update Author" />
{% else %}
    <input type="submit" value="Add Author" />
{% endif %}
like image 23
Tomasz Karbownicki Avatar answered Nov 16 '22 00:11

Tomasz Karbownicki