Python Django-如何将模型传递给CreateView

Python Django-如何将模型传递给CreateView,python,django,Python,Django,我是Django的新手,我被这个问题困扰了一段时间。 我想创建一个通用的create视图,它接受任何模型并从中创建表单,但我不知道如何将model属性设置为作为URL参数传递给视图的模型 URL.py: url(r'^(?P<model>\w+)/new$', views.ModelCreate.as_view(), name='new-record') 提前谢谢你的帮助 首先。。。为了创建通用视图来为任何模型创建模型表单,您需要通过POST或GET请求传入您试图为其创建表单的模型

我是Django的新手,我被这个问题困扰了一段时间。 我想创建一个通用的create视图,它接受任何模型并从中创建表单,但我不知道如何将model属性设置为作为URL参数传递给视图的模型

URL.py:

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

提前谢谢你的帮助

首先。。。为了创建通用视图来为任何模型创建模型表单,您需要通过POST或GET请求传入您试图为其创建表单的模型

然后,您需要在正确的位置设置要为其创建表单的模型。如果深入研究Django的CreateView,您会发现父类ModelFormMixin有一个方法get\u form\u class()。我将在ModelCreate类中重写此方法,并根据通过请求传入的变量在其中设置模型。如您所见,此方法负责从模型创建表单

    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)
    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)