Django - display an error message when form is invalid with "CreateView"
Here is my simplified "ProjectCreate" ClassBasedView :
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ['name', 'creation_date', 'price']
class ProjectCreate(LoginRequiredMixin, SuccessMessageMixin, CreateView):
model = Project
form_class = ProjectForm
success_message = "Project successfully created"
success_url = "project-list"
def get_form(self, form_class=None):
form = super(ProjectCreate, self).get_form(form_class)
form.fields.pop('creation_date')
return form
def form_valid(self, form):
if form.instance.name == "not_valid_name":
return super().form_invalid(form)
form.instance.last_editor = self.request.user
form.instance.last_modification_date = datetime.datetime.now()
return super().form_valid(form)
I want to create the project only if the name isn't "not_valid_name"
If the name is "not_valid_name", i want to display an error message (saying that the name isn't valid), and bring back the user to the 'project create' page
If you need any additional informations to understand my problem, don't hesitate to ask me.
Thanks :)
You can achieve this at different levels:
- at the
Form
level: here is the link to the corresponding page in the documentation. In short, use theclean
method of the fieldname
, the following code should be easy to understand:
from django import forms
from ??? import Project
class ProjectForm(forms.ModelForm):
# I assume you already have some code here
def clean_name(self):
name = self.cleaned_data.get("name")
if name in ["invalid_name_1", "invalid_name_2"]: # etc.
raise ValidationError("Forbidden value for this field.")
return name
class Meta(forms.ModelForm.Meta):
model = Project
With this code (and a few lines more in the template), this is what the client will see:
- at the
Model
level: you could use a custom validator. Check this page for further information, it's quite well written. - at the
View
level, as you were trying to do, there should be a way, but I think it's not the best solution because it's cleaner to keep the validation logic in the form & model fields. A reason for that, for instance, is that you might be willing to keep the same constraint in theadmin
app when editing yourProject
instances. Here's a hint if you prefer that alternative: this page lists all available & useful methods in aCreateView
.