【问题标题】:Django - How to pass a model to CreateViewDjango - 如何将模型传递给 CreateView
【发布时间】:2016-11-11 18:35:27
【问题描述】:

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

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'

提前感谢您的帮助!

【问题讨论】:

    标签: python django


    【解决方案1】:

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

    然后,您需要在正确的位置设置您希望为其创建表单的模型。如果你深入研究 Django 的 CreateView,你会发现父类 ModelFormMixin 有一个方法 get_form_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)
    

    【讨论】:

      猜你喜欢
      • 2014-12-12
      • 2020-03-26
      • 1970-01-01
      • 2019-06-06
      • 2017-03-23
      • 1970-01-01
      • 2019-09-22
      • 2016-11-17
      • 1970-01-01
      相关资源
      最近更新 更多