【问题标题】:Issues with Custom Error Messages on ModelFormModelForm 上的自定义错误消息问题
【发布时间】:2021-09-12 19:37:07
【问题描述】:

我正在尝试覆盖默认错误消息,这样我就可以自己为错误定义一些句子,但我无法覆盖,这真的浪费了我的时间。有人知道我错过了什么吗?

from django import forms
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy
from .models import *
# Create your models here.

class ProfileForm(ModelForm):
    error_messages = {
        'required': ugettext_lazy("This field is mandatory."),
        'invalid': 'Enter a valid number',
        'caps': 'This field if case sensitive' 
        }

    esewa_id = forms.CharField(error_messages=error_messages,
     label='Esewa_Id',
     help_text='This information will be used only for payment purpose.',
     widget=forms.NumberInput(attrs={'class':'NumberField', 'type':'number', 'placeholder':'Enter your Esewa_Id'}),

     )
    class Meta:
        model=Customer
        fields = ['first_name','second_name','email','image','gender','esewa_id']

在 models.py 中,我定义了一个继承自 User 模型的 Customer 模型,并且还使用验证器进行图像验证,并且确实提到了 help_text。

from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from django.core.validators import FileExtensionValidator,MinValueValidator,MaxValueValidator
# Create your models here.
class Customer(models.Model): 
    Gender_Choices=[
        ('Male','Male'),
        ('Female','Female'),
    ]  
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) 
    first_name = models.SlugField(max_length=10, null=True)
    second_name=models.CharField(max_length=10,null=True)
    
    email = models.EmailField(max_length=140, null=True,blank=True)
    image = models.ImageField(upload_to="thumbnails/profile/%y"
                              ,help_text="This will be uploaded as your profile picture. Only .png and .jpg are accepted"
                              ,validators=[FileExtensionValidator(['png','jpg'])]
                              ,blank=True,null=True)
    gender=models.CharField(choices=Gender_Choices,null=True,max_length=50)
    esewa_id=models.PositiveIntegerField(null=True
                                 ,help_text='This information will be used only for payment purpose.'
                                ,validators=[MinValueValidator(9400000000),MaxValueValidator(9999999999)]
                                 )
    auth_token = models.CharField(max_length=100,null=True)
    is_verified = models.BooleanField(default=False)        

    def __str__(self):
        return str(self.user)

【问题讨论】:

    标签: python django visual-studio-code


    【解决方案1】:

    您需要创建一个异常类型的错误类,然后引发该异常

    每https://www.programiz.com/python-programming/user-defined-exception

    # define Python user-defined exceptions
    class Error(Exception):
        """Base class for other exceptions"""
        pass
    
    
    class ValueTooSmallError(Error):
        """Raised when the input value is too small"""
        pass
    
    
    class ValueTooLargeError(Error):
        """Raised when the input value is too large"""
        pass
    
    
    # you need to guess this number
    number = 10
    
    # user guesses a number until he/she gets it right
    while True:
        try:
            i_num = int(input("Enter a number: "))
            if i_num < number:
                raise ValueTooSmallError
            elif i_num > number:
                raise ValueTooLargeError
            break
        except ValueTooSmallError:
            print("This value is too small, try again!")
            print()
        except ValueTooLargeError:
            print("This value is too large, try again!")
            print()
    
    print("Congratulations! You guessed it correctly.")
    

    这是该程序的示例运行。

    Enter a number: 12
    This value is too large, try again!
    
    Enter a number: 0
    This value is too small, try again!
    
    Enter a number: 8
    This value is too small, try again!
    
    Enter a number: 10
    Congratulations! You guessed it correctly.
    

    【讨论】:

    • 好吧,这确实适用于检查数字并根据结果生成异常,但我的情况不同,我实际上是在尝试覆盖默认表单向客户端/(Web 浏览器)显示的 error_messages。
    猜你喜欢
    • 2011-03-16
    • 1970-01-01
    • 2019-12-16
    • 2017-10-02
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    相关资源
    最近更新 更多