Search code examples
pythondjangocruddjango-generic-views

Django CreateView cancel with empty fields


I have a CountryCreateView for my Country model and I'm trying to add a cancel button to it. However if there isn't something filled out in every field and I press the cancel button, I get a pop-up that says Please fill out this field. When I press the cancel button, I don't care what's in the fields, I just want to go to the page I'm redirecting to. On top of this, I want this field non-requirement to be only for this. I don't want anything else to allow blank fields.

views.py:

class CountryCreateView(generic.edit.CreateView):
    model = Country
    fields = ['code', 'name']
    template_name_suffix = '_create'

    def post(self, request, *args, **kwargs):
        if "cancel" in request.POST:
            return HttpResponseRedirect(reverse('appName:country_list'))
        else:
            return super(CountryCreateView, self).post(request, *args, **kwargs)

models.py:

class Country(AutoUpdateModel): # extends models.Model

    code = models.CharField(primary_key=True, max_length=2, validators=[validate_nonempty, validate_string_length_two, validate_string_all_caps]) 
    name = models.CharField(max_length=50, db_column="Name", validators=[validate_nonempty])
    # etc...

country_create.html:

{% extends "appName/base.html" %}


{% block content %}


    <h2 class="title">Create a new Country:</h2>

    <form action="" method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Save" class="btn btn-primary"/>
        <input type="submit" name="cancel" value="Cancel" class="btn btn-secondary"/>
    </form>

{% endblock %}

Solution

  • Please check if this works - add formnovalidate to submit button in html

    <input type="submit" formnovalidate name="cancel" value="Cancel" class="btn btn-secondary"/>