django表单验证 - 验证错误自定义消息不起作用

时间:2018-04-26 09:04:12

标签: python django django-rest-framework

这是一个Django休息项目 我正在创建一个用户注册表单..我写了一个像下面的用户名验证,但我的自定义验证错误没有显示,它显示如下的默认消息...我该如何解决这个问题?

我的另一个问题是:public partial class MainForm : Form { // ... void BackgroundWorkerISOAnalysisDoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; int prog = 0; isoDataTemp.CheckExecution += () => { prog += 12; if (prog > 100) prog = 100; worker.ReportProgress(prog); return !worker.CancellationPending; }; isoDataTemp.Analyze(); if (worker.CancellationPending) e.Cancel = true; } } def validate_username

之间的区别是什么

谢谢

这是默认的Django消息:

def clean_username

这是我的观点:

"{
    "username": [
        "A user with that username already exists."
    ]
}
"

这是我的serilizer:

class UserRegisterApiView(CreateAPIView):
    permission_classes = [AllowAny]
    serializer_class = UserRegisterSerializer
    queryset = User.objects.all()

1 个答案:

答案 0 :(得分:0)

唯一的消息来自模型:

username = models.CharField(
    _('username'),
    max_length=150,
    unique=True,
    help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
    validators=[username_validator],
    error_messages={
        'unique': _("A user with that username already exists."),
    },
)

在您的情况下,您需要在序列化程序中重写用户名的UniqueValidator。

class UserRegisterSerializer(ModelSerializer):
    def __init__(self, *args, **kwargs):
        super(UserRegisterSerializer, self).__init__(*args, **kwargs)
        for validator in self.fields['username'].validators:
            from rest_framework.validators import UniqueValidator
            if type(validator) == UniqueValidator:
                validator.message = 'این نام کاربری آزاد نمیباشد'