[英]Django Createview for generic Model
I've been searching really hard for this, and i can't find it anywhere. 我一直在努力寻找这个,我无法在任何地方找到它。 So, here it goes:
所以,在这里:
I'm trying to build an generic class that takes a generic Model as parameter and creates a form for it. 我正在尝试构建一个泛型类,它将通用模型作为参数并为其创建表单。 For this i'm using Django's ModelForm and CreateView classes.
为此,我使用Django的ModelForm和CreateView类。 The main goal to this, is when i need to create a new form, i just declare a new URL passing the Model name.
这个的主要目标是,当我需要创建一个新表单时,我只是声明一个传递Model名称的新URL。
url(r'^create', GenericCreate(model=Author).as_view(), name='create'),
class GenericCreate(CreateView):
def __init__(self, model, *args, **kwargs):
super(GenericCreate, self).__init__(*args, **kwargs)
self.form_class = to_modelform(self.model)
to_modelform is a function that i implemented that converts a model to a modelform, and it works. to_modelform是我实现的一个函数,它将模型转换为模型形式,并且它可以工作。
This gives me the following error: 这给了我以下错误:
AttributeError at /create This method is available only on the view class. / create中的AttributeError此方法仅在视图类上可用。
Thank you in advance! 先感谢您!
You should not be creating an instance of the view class, as_view
will do that for you. 您不应该创建视图类的实例,
as_view
将为您执行此操作。
You would normally call ViewClass.as_view()
, not ViewClass().as_view()
. 您通常会调用
ViewClass.as_view()
,而不是ViewClass().as_view()
。
Also, CreateView
already takes model
as a parameter, so you should define your url as: 此外,
CreateView
已将model
作为参数,因此您应将您的URL定义为:
url(r'^create', CreateView.as_view(model=Author), name='create'),
For a proper look at how this works, have a look at the as_view
method on CreateView . 要正确了解它的工作原理,请查看CreateView上的
as_view
方法 。 (Full disclosure -- I built ccbv.co.uk
.) (完全披露 - 我建立了
ccbv.co.uk
)
meshy has provided the answer, but note that your to_modelform
function is unnecessary. to_modelform
提供了答案,但请注意您的to_modelform
函数是不必要的。 CreateView works perfectly well with a model or model instance rather than a form, see the documentation . CreateView与模型或模型实例完美匹配,而不是表单,请参阅文档 。
I had this error as well ( TypeError: 'instance' is an invalid keyword argument for this function
); 我也有这个错误(
TypeError: 'instance' is an invalid keyword argument for this function
); for me it was related to defining the Model instead of the Form in form_class
. 对我而言,它与定义Model而不是
form_class
中的Form form_class
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.