django在form里使用ModelForm绑定的表单,可以使用 clean方法验证字段


发布时间:2019-02-15 13:08    作者: Uncle Hui   已过去:1 年,1 月   阅读总量:142 已被赞:0


实例代码:

class GRZXForm(ModelForm):
    class Meta:
        model = UserProfile
        widgets = {
            'myfield': forms.TextInput(attrs={"class": "form-control"})}
        fields = ['nick_name', 'gender', 'adress', 'mobile']
    def clean_nick_name(self):
        nick_name = self.cleaned_data['nick_name']
        nicheng = UserProfile.objects.filter(nick_name=nick_name)
        if nicheng:
            raise forms.ValidationError("该昵称已经被别人使用了,请换一个重新输入。")
        return nick_name

注意事项:

在视图处理时,一定要记得将request.post传进去,否则无法验证数据

if request.method == 'POST':
    # 上传的文件都在request.FILES里面获取,所以这里要多传一个这个参数
    grzxform = GRZXForm(request.POST)
    if grzxform.is_valid():
        username =request.user.username
        user = User.objects.get(username=username)
        if user:
            userProfile = models.UserProfile.objects.filter(user_id=user.id).first()
            if userProfile:
                nick_name = grzxform.cleaned_data['nick_name']
                gender = grzxform.cleaned_data['gender']
               .....
                userProfile.mobile = mobile
                userProfile.save()
                return redirect(reverse('tou'))

            else:
                userProfile = models.UserProfile()
                userProfile.user = user
                nick_name = grzxform.cleaned_data['nick_name']
                gender = grzxform.cleaned_data['gender']
                .....
                userProfile.mobile =mobile
                userProfile.save()
                return redirect(reverse('tou'))
    else:
        grzxform = GRZXForm(request.POST)
        return render(request, 'tou.html', {'grzxform': grzxform})

 

前端使用:

<form action="" method="post" class="form-group" >
{% csrf_token %}
{% for field in grzxform %}
    <label class="form-group" for="{{ field.id_for_label }}">{{ field.label }}</label>
    {{ field }}
    <p>{{ field.errors.as_text }}</p>
{% endfor %}
    <input type="submit" class="btn btn-primary " value="立即保存">
    <p></p>
</form>
 <span>{{ login_form.non_field_errors }}</span>

点赞

0




登陆后方可评论