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

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

问题描述

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

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

基本上你只是创建一个继承自最类似于所需的字段,然后重写clean()方法,以便返回所需的值。这是另一个例子:

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天全站免登陆