Django Createview for generic Model
Asked Answered
A

3

6

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. The main goal to this, is when i need to create a new form, i just declare a new URL passing the Model name.

urls.py

url(r'^create', GenericCreate(model=Author).as_view(), name='create'),

views.py

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.

This gives me the following error:

AttributeError at /create This method is available only on the view class.

Thank you in advance!

Apodaca answered 29/7, 2014 at 10:50 Comment(0)
N
6

You should not be creating an instance of the view class, as_view will do that for you.

You would normally call ViewClass.as_view(), not ViewClass().as_view().

Also, CreateView already takes model as a parameter, so you should define your url as:

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. (Full disclosure -- I built ccbv.co.uk.)

Negotiation answered 29/7, 2014 at 10:58 Comment(2)
Thanks!! It works now.. i did what you suggested and also had to delete "model" from the init function parameters.Apodaca
Glad that worked :) If you're satisfied with the answer, please feed my stackoverflow points addiction, and make it the accepted answer! :PNegotiation
V
2

meshy has provided the answer, but note that your to_modelform function is unnecessary. CreateView works perfectly well with a model or model instance rather than a form, see the documentation.

Venegas answered 29/7, 2014 at 10:59 Comment(1)
Thank you... I'll read it in more detail. I'm new to python and Django. I deleted my to_modelform function and the error TypeError at /create 'instance' is an invalid keyword argument for this function appeared.Apodaca
T
0

I had this error as well (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.

Townsend answered 8/2, 2017 at 20:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.