2011-10-30 34 views
29

Tôi có một hình thức khá đơn giản:Tuỳ chỉnh hình thức xác nhận

from django import forms 

class InitialSignupForm(forms.Form): 
    email = forms.EmailField() 
    password = forms.CharField(max_length=255, widget = forms.PasswordInput) 
    password_repeat = forms.CharField(max_length=255, widget = forms.PasswordInput) 

    def clean_message(self): 
     email = self.clean_data.get('email', '') 
     password = self.clean_data.get('password', '') 
     password_repeat = self.clean_data.get('password_repeat', '') 

     try: 
      User.objects.get(email_address = email) 
      raise forms.ValidationError("Email taken.") 
     except User.DoesNotExist: 
      pass 

     if password != password_repeat: 
      raise forms.ValidationError("The passwords don't match.") 

Đây có phải là cách tùy chỉnh hình thức xác nhận được thực hiện? Tôi cần đánh giá trên email rằng không có người dùng nào hiện đang tồn tại với địa chỉ email đó. Tôi cũng cần đánh giá rằng passwordpassword_repeat phù hợp. Làm thế nào tôi có thể đi về việc này?

+0

tôi thích làm xác nhận trên mothel hơn là trên hình thức: http://beutil.blogspot.com/2011/10/django-moving- business-rules-from-views.html – danihp

Trả lời

83

Để xác nhận một lĩnh vực duy nhất trên riêng của nó bạn có thể sử dụng một phương pháp clean_FIELDNAME() trong mẫu của bạn, vì vậy cho email:

def clean_email(self): 
    email = self.cleaned_data['email'] 
    if User.objects.filter(email=email).exists(): 
     raise ValidationError("Email already exists") 
    return email 

sau đó cho các lĩnh vực đồng phụ thuộc dựa vào nhau, bạn có thể ghi đè lên các hình thức clean() phương pháp được chạy sau khi tất cả các lĩnh vực (như email trên) đã được xác nhận riêng lẻ:

def clean(self): 
    form_data = self.cleaned_data 
    if form_data['password'] != form_data['password_repeat']: 
     self._errors["password"] = ["Password do not match"] # Will raise a error message 
     del form_data['password'] 
    return form_data 

tôi không chắc chắn nơi bạn có clean_message() từ, nhưng điều đó có vẻ như nó là một phương pháp xác nhận thực hiện cho một message trường dường như không tồn tại trong biểu mẫu của bạn.

Have a đọc qua này để biết thêm chi tiết:

https://docs.djangoproject.com/en/dev/ref/forms/validation/

+4

chỉ là một thông báo nhỏ ... 'form_data ['password']! = form_data ['password']' probabbly nên có một cái gì đó như 'password2' cho trường với mật khẩu lặp lại ... – andi

+0

Ya .. Điều đó phải là: form_data ['password']! = Form_data ['password_repeat'] – pavanw3b

+0

Tôi đã thay đổi một thành 'password_repeat', cảm ơn! –

Các vấn đề liên quan