Django - CrispyForms - DecimalField -验证错误消息

tcbh2hod  于 2023-05-30  发布在  Go
关注(0)|答案(1)|浏览(119)

我有以下模型,并希望确保a)用户只能输入数字和小数点,或者b)向用户显示自定义验证错误,以仅输入小数点。我正在使用init方法,并希望在此方法中包含此类验证。这可能吗?CurrencyCode是一个ForeignKey字段,因此它必须在呈现的表单上显示为下拉列表。
x1c 0d1x下面是代码:
MODELS.PY:

class Forex(models.Model):
    currency_code = models.ForeignKey(Currency, on_delete=models.CASCADE)
    forex_rate = models.DecimalField(max_digits=8, decimal_places=4)
    last_updated_on = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name_plural = "Forex Rates"

    def __str__(self):
        return self.currency_code.currency_code

FORMS.PY:

class ForexForm(forms.ModelForm):

    class Meta:
      model = Forex
      fields = ['currency_code', 'forex_rate']

    def __init__(self, *args, **kwargs):
        super(ForexForm, self).__init__(*args, **kwargs)
        self.fields['currency_code'].error_messages = {'required': 'Currency Code Cannot Be Blank',
                                                   'unique': 'Forex Rate Already Exists!'
                                                   }
        self.fields['forex_rate'].error_messages = {'required': 'Forex Rate Cannot Be Blank'}

VIEWS.PY:

def forex_add(request):
    form = ForexForm(request.POST or None)
    if form.is_valid():
        form.save()
        messages.success(request, msg_add)
        return redirect('forex_list_page')
    context = {
        'form': form
    }
    return render(request, 'main/forex_add.html', context)

FOREX_ADD/HTML:

<form action="" method="POST" novalidate>

    {% csrf_token %}
    <div class="row">
        <div class="col-4">
            {{ form.currency_code|as_crispy_field }}
        </div>
        <div class="col-8">
            {{ form.forex_rate|as_crispy_field }}
        </div>
    </div>
    <div class="col-12">
        <button class="btn btn-outline-success" type="submit"><i
                class="fa-solid fa-floppy-disk"></i> Save
        </button>
        <a class="btn btn-outline-danger" href="{% url 'forex_list_page' %}">
            <i class="fa-solid fa-reply"></i> Cancel</a>
    </div>

</form>
wwodge7n

wwodge7n1#

可以,可以在表单的__init__方法中包含自定义验证,以确保forex_rate字段仅接受十进制值,或者在输入无效值时显示自定义验证错误。以下是如何修改ForexForm类以包含此验证:

from django.core.exceptions import ValidationError

class ForexForm(forms.ModelForm):
    class Meta:
        model = Forex
        fields = ['currency_code', 'forex_rate']

    def __init__(self, *args, **kwargs):
        super(ForexForm, self).__init__(*args, **kwargs)
        self.fields['currency_code'].error_messages = {'required': 'Currency Code Cannot Be Blank',
                                                       'unique': 'Forex Rate Already Exists!'}

        self.fields['forex_rate'].error_messages = {'required': 'Forex Rate Cannot Be Blank'}

        # Add custom validation for forex_rate field
        self.fields['forex_rate'].validators.append(self.validate_forex_rate)

    def validate_forex_rate(self, value):
        # Custom validation to ensure the forex_rate is a decimal value
        try:
            float(value)
        except (TypeError, ValueError):
            raise ValidationError('Please enter a valid decimal value for the Forex Rate.')

        # Additional validation if needed
        # ...

在更新后的代码中,自定义验证方法validate_forex_rate被添加到表单中。此方法检查输入的值是否可以转换为浮点数(十进制值)。如果转换失败,它将引发带有自定义错误消息的ValidationError
通过将self.validate_forex_rate追加到forex_rate字段的验证器列表中,当表单被验证时,将触发此自定义验证。如果验证失败,将向用户显示ValidationError中定义的错误消息。
注意:确保在文件的开头从django.core.exceptions导入ValidationError。

相关问题