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.
You can achieve this at different levels:
- at the
Formlevel: here is the link to the corresponding page in the documentation. In short, use the
cleanmethod of the field
name, 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
- at the
Modellevel: you could use a custom validator. Check this page for further information, it's quite well written.
- at the
Viewlevel, 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 the
adminapp when editing your
Projectinstances. Here's a hint if you prefer that alternative: this page lists all available & useful methods in a