关于如何在 django 中编写自定义表单字段的教程? [英] Tutorial about how to write custom form fields in django?

查看:26
本文介绍了关于如何在 django 中编写自定义表单字段的教程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么好文章解释django中的自定义表单字段,而不是自定义模型字段?我通过谷歌找不到任何.

解决方案

表单字段易于自定义:

class UpperCaseField(forms.CharField):def清洁(自我,价值)尝试:返回值.upper()除了:引发验证错误

基本上,您只需创建一个类,该类继承自与您想要的最相似的字段,然后重写 clean() 方法,使其返回您想要的值.这是另一个例子:

class MyObjectField(forms.ModelChoiceField):# 在这种情况下,'value' 是一个字符串,表示# MyObject 的主键定义清洁(自我,价值):尝试:返回 MyObject.objects.get(pk=value)除了:引发验证错误

自定义小部件另一方面,更有用一点,但更难做,因为还有一些方法需要编写,以便它们顺利工作.>

Is there any good articles that explain custom form fields in django, not custom model fields? I couldn't find any through google.

解决方案

Form fields are easy to customize:

class UpperCaseField(forms.CharField):
    def clean(self, value)
        try:
            return value.upper()
        except:
            raise ValidationError

basically you just create a class that inherits from the field that most resembles what you want, then rewrite the clean() method so that it returns the value you want. Here is another example:

class MyObjectField(forms.ModelChoiceField):
    # in this case, 'value' is a string representing
    # the primary key of a MyObject
    def clean(self, value):
        try:
            return MyObject.objects.get(pk=value)
        except:
            raise ValidationError

custom widgets on the other hand, are a little more useful, but a little more hard to do because there are a few more methods that need to be written so that they work smoothly.

这篇关于关于如何在 django 中编写自定义表单字段的教程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆