yoni78
yoni78

Reputation: 43

Django - How to pass a model to CreateView

I am new to Django, and I got stuck on this problem for a while now. I want to create a generic Create View, that accepts any model and creates a form from it, but I don't know how set the model attribute to the model passed to the view as a URL parameter.

urls.py:

url(r'^(?P<model>\w+)/new$', views.ModelCreate.as_view(), name='new-record')

views.py:

class ModelCreate(CreateView):
    model = ???

    fields = []
    for field in model._meta.get_fields():
        fields.append(field.name)

    template_name = 'new_record.html'

Thanks for the help in advance!

Upvotes: 1

Views: 1226

Answers (1)

korono89
korono89

Reputation: 216

To begin with... in order create a generic view to create models forms for any model you will need to pass in the Model which you are trying to create the form for through the request with either POST or GET.

Then, you will need to set the model you wish to create the form for in the correct spot. If you dig down into Django's CreateView you will find that the parent class ModelFormMixin has a method get_form_class(). I would override this method within your ModelCreate class and set the model there from a variable you have passed in through the request. As you can see this method is responsible for creating the Form from the model.

    def get_form_class(self):
    """
    Returns the form class to use in this view.
    """
    if self.fields is not None and self.form_class:
        raise ImproperlyConfigured(
            "Specifying both 'fields' and 'form_class' is not permitted."
        )
    if self.form_class:
        return self.form_class
    else:
        if self.model is not None:
            # If a model has been explicitly provided, use it
            model = self.model
        elif hasattr(self, 'object') and self.object is not None:
            # If this view is operating on a single object, use
            # the class of that object
            model = self.object.__class__
        else:
            # Try to get a queryset and extract the model class
            # from that
            model = self.get_queryset().model

        if self.fields is None:
            raise ImproperlyConfigured(
                "Using ModelFormMixin (base class of %s) without "
                "the 'fields' attribute is prohibited." % self.__class__.__name__
            )

        return model_forms.modelform_factory(model, fields=self.fields)

Upvotes: 1

Related Questions