django 为什么在“clean”函数中没有引发验证错误?

gc0ot86w  于 2023-01-03  发布在  Go
关注(0)|答案(1)|浏览(155)

我将用户配置文件窗体与UpdateView一起使用时遇到了一个问题,即即使满足了引发错误的条件,也没有引发验证错误。导致此意外行为的原因可能是什么?
forms.py.

class UserProfileForm(forms.ModelForm):
    
    class Meta:
        model = UserProfile
        fields = ("avatar","username","first_name","last_name","age","gender")
        # fields = ("avatar",)
        Gender = (
            ('one','Male'),
            ('two','Female'),
            )
            
        widgets ={
            'age' : forms.TextInput(attrs={'class':'form-control'}),
            'gender' : forms.Select(choices=Gender,attrs={'class': 'form-control'}),
        }
     # TRIED THIS AS WELL    
    # def clean_age(self):
    #     age = self.cleaned_data["age"]
    #     print(age,'hm here')
    #     if age < 18:
    #         print(age,'hm here')
    #         raise forms.ValidationError("You're age should be 18 plus")
    #     return age

    def clean(self):
        cleaned_data = super().clean()

        age = cleaned_data.get('age')
        print('haye',age)
        if age < 18:
            print(age,'hm here')
            # raise forms.ValidationError("You're age should be 18 plus")
            age = "You're age should be 18 plus"
            self.add_error('age',age)
            raise forms.ValidationError("You're age should be 18 plus")

views.py 在这里我更新用户模型字段,然后用户配置文件字段,然后分别保存它们.

class UserProfileUpdateView(UpdateView):
    refirect_field_name ='accounts:profile'
    template_name = 'accounts/profiles/profile_update.html'
    form_class = UserProfileForm
    model = UserProfile

    def get_object(self, *args, **kwargs):
        return self.request.user.userprofile
    
    def get_context_data(self, *args, **kwargs):
        context = super(UserProfileUpdateView, self).get_context_data(*args, **kwargs)
        update_form = UserProfileForm(instance = self.request.user.userprofile)
        context['form']=update_form
        return context
    
    def form_valid(self, form):
            username = form.cleaned_data['username']
            print('username :',username)
            first_name = form.cleaned_data['first_name']
            print('first name :',first_name)
            last_name = form.cleaned_data['last_name']
            print('last name :',last_name)
            age = form.cleaned_data['age']
            print('age :',age)
            gender = form.cleaned_data['gender']
            print('gender :',gender)
            # usermodel save
            user = User.objects.get(username=self.request.user)
            print('GOT reqested User',user)
            user.username = username
            print('changed username :',user.username)
            user.age = age
            print('changed age :',user.age)
            user.gender = gender
            print('changed gender:',user.gender)
            user.first_name = first_name
            print('changed first name :',user.first_name)
            user.last_name = last_name
            print('changed last name :',user.last_name)
            user.save()
            # userprofile save
            profile = UserProfile.objects.get(user=self.request.user)
            print('GOT reqested User',profile)
            profile.username = username
            print('changed username :',profile.username)
            profile.age = age
            print('changed age :',profile.age)
            profile.gender = gender
            print('changed gender:',profile.gender)
            profile.first_name = first_name
            print('changed first name :',profile.first_name)
            profile.last_name = last_name
            print('changed last name :',profile.last_name)
            profile.save()
            form.save()
            return super().form_valid(form)

models.py

class UserProfile(models.Model):

    user = models.OneToOneField(auth.models.User,related_name='userprofile', on_delete=models.CASCADE)
    avatar = models.ImageField(("displays"), upload_to='displays', height_field=None, width_field=None, max_length=None,default ='user.jpg')
    create_date = models.DateTimeField(default = timezone.now)
    Gender = (
    ('one','Male'),
    ('two','Female'),
    )
    first_name = models.CharField(("first_name"), max_length=50,null=True)
    last_name = models.CharField(("last_name"), max_length=50,null=True)
    username = models.CharField(("username"), max_length=50,null=True)
    age = models.IntegerField(("age"),null=True)
    gender = models.CharField(("gender"), max_length=50,choices=Gender,null=True)

    def __str__(self):
        return f'{self.user.username} UserProfile'
    
    def clean_fields(self, exclude=None):

        if self.age < 18:
            raise ValidationError(
                {"age": "You're age should be 18+"}
            )
        return super().clean_fields(exclude=exclude)

    def save(self,*args, **kwargs):
        if not self.username:
            self.username  = self.user.username
        if not self.age:
            self.age = self.user.age
        if not self.gender:
            self.gender  = self.user.gender
        if not self.first_name:
            self.first_name  = self.user.first_name
        if not self.last_name:
            self.last_name  = self.user.last_name
        super(UserProfile,self).save(*args, **kwargs)

请告诉我如何解决这个问题,并提出错误的无效细节。如果需要更多的信息,然后告诉我在评论部分,我会更新我的问题与该信息。

h5qlskok

h5qlskok1#

通过使用这两个方法,无需重写窗体的clean方法,并且每当创建示例时都会验证该对象。

**方法1:**覆盖www.example.com中UserProfile类的clean_fields方法models.py

def clean_fields(self, exclude=None):

    if self.age < 18:
        raise ValidationError(
            {"age": "You're age should be 18+"}
        )

    return super().clean_fields(exclude=exclude)

**方法2:**在定义年龄字段时添加最小值验证

age = models.PositiveIntegerField(
    help_text="Age of the user.",
    validators=[
        MinValueValidator(
            18, "You're age should be 18+"
        )
    ]
)

您的观点:

def form_valid(self, form):
    # userprofile save
    profile = form.save(commit=False)
    # usermodel save
    user = self.request.user
    user.username = profile.username
    user.age = profile.age
    user.gender = profile.gender
    user.first_name = profile.first_name
    user.last_name = profile.last_name
    user.save()
    return super().form_valid(form)

相关问题