vaemps
vaemps

Reputation: 47

Django-forms: ValidationError not working / check if attribute exists

I am trying to get an error for the form if name of a created process already exists. Now what happens is that the form just doesn't submit, but it doesn't raise any errors to the form itself noting what is going on. I have looked all different ways to get the ValidationError to do something, but I cannot get it work at all. Form works otherwise as it submits if value doesn't already exist. What am I missing here?

Here is models.py

class Process(models.Model):
    name = models.CharField('Process name', max_length=100, unique=True, error_messages={'unique':"Name already in use"})

Here is forms.py

class NewProcess(forms.ModelForm):

    class Meta:
        model = Process
        fields = [
            'name',
        ]

    def __init__(self, *args, **kwargs):
        super(NewProcess, self).__init__(*args, **kwargs)

    def clean_name(self):
        process_name = self.cleaned_data.get('name')

        existing = Process.objects.filter(name=process_name).exists()

        if existing:
            raise forms.ValidationError(u"Name already in use")
        return process_name

Here is views.py

def process_create(request, *args, **kwargs):

createprocess = NewProcess(request.POST or None)

processes = Process.objects.all()

if request.method == 'POST':
    createprocess = NewProcess(request.POST)
    if createprocess.is_valid():
        process = createprocess.save(commit=False)
        #other functions here
        creatprocess.save()

            context = {
                'processes':processes,
            }

            return render(request, "process/process-list.html", context)

context = {
    'createprocess':createprocess,
}

return render(request, "process/process-create.html", context)

Upvotes: 0

Views: 105

Answers (1)

Blye
Blye

Reputation: 672

You defined a method called clean_name to raise the error however the validation method you're using in the views.py is is_valid() which does not return false for duplicate names.

Upvotes: 0

Related Questions