django清洁模型模型的方法

时间:2018-10-16 00:32:00

标签: django django-forms

我只使用了现成的Django表单API。我现在正在尝试验证Django模型表单-update_profile上的表单字段数据。我的模型包含验证器,在哪里(以及为什么)执行清理或保存操作以便为最终用户提供字段级别的消息传递?目前,我的错误字典为空。

class CustomUser(AbstractBaseUser):
    email = models.EmailField(_('email'), max_length=254, unique=True)
    username = models.CharField(_('username'),max_length=15, unique=True,
        validators=[RegexValidator('^[_a-z0-9]+$', message= '15 characters max. Username must be a-z(lowercase), 0-9, can contain underscore', code='invalid_username')])
    about_me = models.CharField(_('about me'),max_length=140)
    avatar = models.ImageField(upload_to='avatars/', blank=True, null=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=50, blank=True)
        phone_regex = RegexValidator(regex='^\+?1?\d{9,15}$', message='Phone number must be between 9 and 15 digits')
    phone_number = models.CharField(_('phone_number'),max_length=15,  blank=True,
        validators=[phone_regex])
    is_active = models.BooleanField(_('active'), default=False)
    is_staff = models.BooleanField(_('staff'), default=False)

views.py

def update_profile(request):
    user=request.user
    if user.is_authenticated == True:
    if request.method == 'POST':
        form = CustomUserChangeForm(request.POST, instance=user)
        if form.is_valid():
            form.save()
            messages.success(request, 'Your profile was successfully updated.')
            return redirect('update profile')
        else:
            messages.error(request, "Please correct the error below.")

    form = CustomUserChangeForm(instance=user)
    return render(request, 'profile.html', {'form': form})

forms.py

class CustomUserChangeForm(forms.ModelForm):

class Meta:
    model = CustomUser
    fields = ('email', 'first_name', 'last_name', 'about_me','phone_number')

2 个答案:

答案 0 :(得分:1)

问题出在此代码中。您将丢弃先前已验证的表单,创建新表单并将其传递给模板。

form = CustomUserChangeForm(instance=user)
return render(request, 'profile.html', {'form': form})

答案 1 :(得分:1)

您需要将无效的表格退还给用户。您应该将空表单的实例放入else块中,以便仅在GET上发生。

if request.method == 'POST':
    form = CustomUserChangeForm(request.POST, instance=user)
    if form.is_valid():
        ...
else:
    form = CustomUserChangeForm(instance=user)
return render(request, 'profile.html', {'form': form})

现在模板{{ form.errors }}中将显示您的验证错误。