将 mixin 与 Django 表单类一起使用 [英] Using a mixin with a Django form class

查看:28
本文介绍了将 mixin 与 Django 表单类一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑创建一个 mixin 表单类,以便我可以将一组通用字段添加到各种非常不同的表单中.仅将其用作基类是行不通的,因为我希望能够像这样使用其他表单作为基类:

class NoteFormMixin(object):note = forms.CharField()类 MainForm(forms.Form):名称 = forms.CharField()年龄 = forms.IntegerField()类 SpecialForm(MainForm, NoteFormMixin):favorite_color = forms.CharField()

我唯一的问题是:这是如何工作的?到目前为止,如果我使用 mixin,则它无法识别从该 mixin 设置的字段:

<预><代码>>>>ff1 = SpecialForm()>>>ff1.fields{'name': <django.forms.fields.CharField 对象在 0x178d3110>, 'age': <django.forms.fields.IntegerField 对象在 0x178d3190>, 'favorite_color': <django.forms.fields.fields.对象在 0x178d3210>}

这是做不到的事情吗?

解决方案

问题是您的 NoteFormMixin 是从 object 而不是 forms.Form 派生的.你需要把它改成这样:

class NoteFormMixin(forms.Form):note = forms.CharField()

I'm thinking about creating a mixin form class so that I can add a common set of fields to a variety of otherwise very different forms. Just using it as a base class won't work because I want to be able to use other forms as base classes like so:

class NoteFormMixin(object):
    note = forms.CharField()

class MainForm(forms.Form):
    name = forms.CharField()
    age = forms.IntegerField()

class SpecialForm(MainForm, NoteFormMixin):
    favorite_color = forms.CharField()

My only question is: how does this work? So far it looks like if I use a mixin, then it doesn't recognize the fields set from that mixin:

>>> ff1 = SpecialForm()
>>> ff1.fields
{'name': <django.forms.fields.CharField object at 0x178d3110>, 'age': <django.forms.fields.IntegerField object at 0x178d3190>, 'favorite_color': <django.forms.fields.CharField object at 0x178d3210>}

Is this just something that can't be done?

解决方案

The issue is that your NoteFormMixin is deriving from object instead of forms.Form. You need to change it to be like so:

class NoteFormMixin(forms.Form):
    note = forms.CharField()

这篇关于将 mixin 与 Django 表单类一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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