Harish Kumar
Harish Kumar

Reputation: 348

accessing uncleaned form data in form.py in django using clean() method

My question may be uncleared. So please read example also. I am using python 3.4 and django 1.7

I am receiving a foreign key from a form selection field. Uncleaned data gives me id of foreign element but cleaned data gives me the str() i.e. name of foreign element.

I want foreign element's object to verify its another property by comparing with form's another cleaned data.

For example, I have a Institute model which contains a private_key( CharField ). Now, I have a teacher model which contains Institute as ForeignKey and need to verify that private_key during registration.

NOTE: private_key is the variable name of type CharField

In form for registration for teacher, Institute is coming as ForeignKey along with a Charfield which contains private_key input given by user.

I have to check that user's private_key input and private_key stored in selected Institute's model.If they are not same then raise "invalid private key" error.

I am using clean() method in form.py (in the class in which I have customize registration form ). But there, I have cleaned data only. Clean data gives me name of the institute instead of id of institute.

How can do it?

If my question is not good than please give answer/comment with reason instead of only down voating it.

Upvotes: 0

Views: 658

Answers (1)

ruddra
ruddra

Reputation: 52028

If you use ModelForm, then you should directly get the object which is related by the foreignkey. So what you can do in cleaned data is:

def clean(self):
    p_key= self.cleaned_data['private_key']
    institute= self.cleaned_data['institute']
    if p_key == institute.private_key :
        return super().clean()
    else:
        raise ValidationError('Invalid key')

If you are using Form, then you should get institute id in your cleaned data.

Upvotes: 0

Related Questions