我是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'
提前感谢您的帮助!
答案 0 :(得分: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)