Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if I'm doing a create or an update with django generic views (CreateView vs UpdateView) from my template?

I'm sharing the same template for my CreateView and UpdateView using django's generic views. I want the "submit" button in my template to say "Add" when I'm using the CreateView and "Update" when I'm using the UpdateView. Is there any way in my template to distinguish which view is being used (CreateView vs UpdateView)?

I know I could use a separate template using template_name_suffix and put the common stuff in a separate include or something but just wanted to see if there was a way to do it without creating a separate template.

like image 222
mgalgs Avatar asked Jun 11 '14 20:06

mgalgs


People also ask

What does CreateView do in Django?

CreateView. A view that displays a form for creating an object, redisplaying the form with validation errors (if there are any) and saving the object. This view inherits methods and attributes from the following views: django.

What is generic view in Django?

Django's generic views were developed to ease that pain. They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to write too much code.

What does {% mean in Django?

{% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What is generic editing?

Genome editing (also called gene editing) is a group of technologies that give scientists the ability to change an organism's DNA. These technologies allow genetic material to be added, removed, or altered at particular locations in the genome. Several approaches to genome editing have been developed.


1 Answers

When creating a new object, object will always be None, at the moment the template is rendered. You could check for the existence of {{ object }} in your template:

{% if object %}Update{% else %}Add{% endif %}
like image 128
Ion Scerbatiuc Avatar answered Sep 18 '22 13:09

Ion Scerbatiuc