2014-09-18 2 views
0

사용자가 기본 (이름 및 이메일) 데이터를 변경할 수있는 간단한 양식을 작성 중입니다. 내가 있는지 확인하려면 : 여전히사용자 이메일 주소 변경

  • 이메일 데이터베이스에서 고유
  • 사용자가 내가 이것에 대한 ModelForm를 사용하고 싶었

자신의 이메일을 변경할 수 있습니다 손길이 닿지 않은

  • 사용자가 자신의 이메일을 남길 수 있습니다.

    class UserDataForm(ModelForm): 
        class Meta: 
         model = User 
         fields = ['first_name', 'last_name', 'email'] 
    
        def clean_email(self): 
         cd = self.cleaned_data 
         email = cd['email'] 
         # Not sure how to check is there is an other account which uses this email EXCEPT this particular user account 
    

    는 내가 거기에 동일한 이메일을 사용하는 다른 계정이며,이 계정이 양식을 채우는 사용자가 소유하지 않을 때 유효성 검사 오류 메시지를 표시해야합니다 : 나는 같은 완료했습니다.

    나는 이것을 달성하는 방법을 모른다.

  • 답변

    2

    이 시도 :이 question에서

    class UserDataForm(ModelForm): 
        class Meta: 
         model = User 
         fields = ['first_name', 'last_name', 'email'] 
    
        def clean_email(self): 
         cd = self.cleaned_data 
         email = cd['email'] 
    
         # object is exists and email is not modified, so don't start validation flow 
         if self.instance.pk is not None and self.instance.email == email: 
          return cd 
    
         # check email is unique or not 
         if User.objects.filter(email=value).exists(): 
          raise forms.ValidationError("Email address {} already exists!".format(value)) 
         return cd 
    

    봐, 나는 그것이 도움이 될 것이라 생각합니다.

    또 다른 방법은 깨끗한 방법으로 이메일을 확인하려고 : 사용자가 성과 이름 만 변경하고자하는 경우에는 어떻게

    def clean(self): 
        cleaned_data = self.cleaned_data 
    
        if 'email' in self.changed_data and User.objects.filter(email=value).exists(): 
         raise forms.ValidationError("Email address {} already exists!".format(value)) 
    
    return cleaned_data 
    
    +0

    ? 전자 메일은 변경되지 않지만 양식은 유효하지 않습니다 (해당 전자 메일 주소가있는 사용자 개체가 있기 때문에). – dease

    +0

    내 대답을 업데이트했습니다. –