Jagulari
Jagulari

Reputation: 81

django form validation - compare inserted data

Question about forms and validation in Django, python.

I have a one field form, to where people can insert peoples names. But it is needed that they can't enter names, which are not supported by a third party website. My forms.py:

class MyModelForm(forms.ModelForm):

    class Meta:

        model = MyModel
        fields = ('title', )


    def clean_title(self):
        cd = self.cleaned_data

        # fields is the line, which checks from a 3rd party db , 
        #   if the name inserted is supported.
        # cleaned_data in the parentheses should be the name, inserted by the user.

        fields = client.search(cleaned_data).name

        # If the client returns the same name as the user has inserted, 
        #   the post must be valid.
        # If the user inserts name, which is not in the 3rd party db, 
        #   the client sends an error as a response and the post can't be accepted.

        if (self.cleaned_data.get('title') != fields)

            raise ValidationError(
                "This name is not supported"
            )

        return self.cleaned_data

I know, that code is a mess, it's because I've tried many different ways already.

I add views.py

def add_model(request):

if request.method == "POST":
    form = MyModelForm(request.POST)
    if form.is_valid():

        # commit=False means the form doesn't save at this time.
        # commit defaults to True which means it normally saves.
        model_instance = form.save(commit=False)
        model_instance.timestamp = timezone.now()
        model_instance.save()
        return HttpResponseRedirect('/polls/thanks')
else:
    form = MyModelForm()

return render(request, "polls/polls.html", {'form': form})

and models.py

class MyModel(models.Model):
title = models.CharField(max_length=25, unique=True, error_messages={'unique':"See nimi on juba lisatud."})
timestamp = models.DateTimeField()

just in case, these are needed.

I hope, you understand, what I'm trying to achieve and maybe you can support me with some good tips or great example of code. Thank You! :)

Upvotes: 0

Views: 819

Answers (1)

catavaran
catavaran

Reputation: 45575

Field value in clean_ method is available as self.cleaned_data['field_name']:

class MyModelForm(forms.ModelForm):

    class Meta:    
        model = MyModel
        fields = ('title', )

    def clean_title(self):
        title = self.cleaned_data['title']
        try:
            name = client.search(title).name
        except HTTPError:
            raise ValidationError("Can't validate the name. Try again later")
        if title != name:
            raise ValidationError("This name is not supported")
        return title

Upvotes: 1

Related Questions