user2361174 user2361174 -4 years ago 247
Python Question

Django CreateView cancel with empty fields

I have a

for my
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.

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'))
return super(CountryCreateView, self).post(request, *args, **kwargs)

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


{% 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"/>

{% endblock %}

Answer Source

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

<input type="submit" formnovalidate name="cancel" value="Cancel" class="btn btn-secondary"/>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download