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

2

6

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.

Beset answered 11/6, 2014 at 20:47 Comment(0)
P
15

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 %}
Pons answered 11/6, 2014 at 21:4 Comment(1)
Better proposal instead of overriding :)Buerger
B
2

Override get_context_data and add a flag in your view:

def get_context_data(self, **kwargs):
    context = super(YourClass, self).get_context_data(**context)
    context['create_view'] = True
    return context

Change YourClass to your Class View name

Then in your template you can:

{% if create_view %}
Buerger answered 11/6, 2014 at 20:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.