开发者

How to make form validation in Django dynamic?

开发者 https://www.devze.com 2023-01-01 10:32 出处:网络
I\'m trying to make a form that handles the checking of a domain: the form should fail based on a variable that was set earlier in another form.

I'm trying to make a form that handles the checking of a domain: the form should fail based on a variable that was set earlier in another form.

Basically, when a user wants to create a new domain, this form should fail if the entered domain exists.

When a user wants to move a domain, this form should fail if the entered domain doesn't exist.

I've tried making it dynamic overload the initbut couldn't see a way to get my passed variabele to the clean function.

I've read that this dynamic validation can be accomplished using a factory method, but maybe someone can help me on my way with this?

Here's a simplified version of the form so far:

#OrderFormStep1 presents the user with a choice: create or move domain

class OrderFormStep2(forms.Form):

    domain = forms.CharField() 
    extension = forms.CharField() 

    def clean(self):
       cleaned_data = self.cleaned_data
       domain = cleaned_data.get("domain")
       extension = cleaned_data.get("extension")

       if domain and extension:

       code = 开发者_如何学JAVAwhoislookup(domain+extension);

       #Raise error based on result from OrderFormStep1
       #raise forms.ValidationError('error, domain already exists')
     #raise forms.ValidationError('error, domain does not exist')

       return cleaned_data


Overriding the __init__ is the way to go. In that method, you can simply set your value to an instance variable.

def __init__(self, *args, **kwargs):
    self.myvalue = kwargs.pop('myvalue')
    super(MyForm, self).__init__(*args, **kwargs)

Now self.myvalue is available in any form method.


Do you have a model that stores the domains? If so, you want to use a ModelForm and set unique=True on whichever field stores the actual domain in the model. As of Django 1.2, you can even do any additional validation inside the model, rather than the form.

0

精彩评论

暂无评论...
验证码 换一张
取 消