Custom button in Class based UpdateView django

365 Views Asked by At

Problem: My UpdateView looks the same as my CreateView. I would like to change the submit button from "Check" to "Update".

Here are my views in the views.py file:

class CapsUnifCreateView(CreateView):
    template_name = 'capsules/uniformity_form.html'
    model = models.Uniformity
    fields = (
        'caps_name',
        'mass_1_caps_empty',
        'mass_20_caps_full',
        'mass_max1',
        'mass_min1',
    )

class CapsUnifUpdateView(UpdateView):
    fields = (
        'caps_name',
        'mass_1_caps_empty',
        'mass_20_caps_full',
        'mass_max1',
        'mass_min1',
    )
    model = models.Uniformity

Note, that I do not use a separate template for the UpdateView.

Something like

{% if CreateView %} Check {% else %} Update {% endif %}

in the html file would be nice, but I don't know how to implement it.

Thanks in advance!

2

There are 2 best solutions below

0
On BEST ANSWER

Found it! In the ModelName_form.html (html file that is linked to CreateView):

    {% if not form.instance.pk %}
      <input type="submit" class="btn btn-primary" value="Check">
    {% else %}
      <input type="submit" class="btn btn-primary" value="Update">
    {% endif %}

This means, if there is no primary key in the context (during CreateView), it shows "Check", else if there is a primary key (during UpdateView), it shows "Update".

Thanks for your efforts!

1
On

Use get context data in your view

class CapsUnifCreateView(CreateView):
template_name = 'capsules/uniformity_form.html'
model = models.Uniformity
fields = (
    'caps_name',
    'mass_1_caps_empty',
    'mass_20_caps_full',
    'mass_max1',
    'mass_min1',
)
def get_context_data(self, **kwargs):
    context = super(CapsUnifCreateView, self).get_context_data(**kwargs)
    context['is_update'] = False
    return context

class CapsUnifUpdateView(UpdateView):
    fields = (
        'caps_name',
        'mass_1_caps_empty',
        'mass_20_caps_full',
        'mass_max1',
        'mass_min1',
    )
    model = models.Uniformity
    def get_context_data(self, **kwargs):
        context = super(CapsUnifUpdateView, self).get_context_data(**kwargs)
        context['is_update'] = True
        return context

In your template check

{% if is_update %} Update {% else %} Create {% endif %}