使用Django表单类的mixin [英] Using a mixin with a Django form class

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

问题描述

我正在考虑创建一个mixin表单类,以便我可以添加一组通用的字段到各种其他非常不同的形式。只需使用它作为基类就不能正常工作,因为我想要使用其他表单作为基类,如下所示:

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

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

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

我唯一的问题是:这是如何工作的?到目前为止,它看起来像是使用mixin,然后它不能识别从该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对象在0x178d3210>}

这只是一些不能完成?

解决方案

问题是您的NoteFormMixin是从对象而不是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()

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

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