我有允许动态创建表单的问卷调查应用程序。在我当前的系统中,我将它链接到一个项目。这是我的模型的一个例子。我想将问卷应用程序与我当前 django 项目中其他应用程序的依赖项完全分开。
#project.models
class Project(models.Model):
name = models.CharField(max_length.....
category = models.CharField(max_length
question_sets = models.ManyToManyField(Question_Set)
#questionnaire.models
class Question(models.Model):
question = models.CharField(max_length....
question_type = models.IntegerField(choices=.....
class Question_set(models.Model):
name = models.CharField(....
questions = models.ManyToManyField(Question)
在我的问卷调查表中,对于这个例子,我有两个基本函数 Question_set create 和 Question create。在 Question_set 创建函数中,我有一个表单,允许我将创建的问题添加到 Question_set,然后保存 Question_set。目前,我还将 url 中的 project_id 传递给该视图,以便获取 Project 实例并添加 Question_set
#questionnaire.views
def question_set_create(request, project_id, form_class=AddSetForm, template_name=....):
if request.method = "POST":
form = form_class(request.POST)
if form.is_valid():
set = form.save()
project = Project.objects.get(id=project_id)
project.question_sets.add(set)
....
#questionnaire.urls
#pattern for question_set_create
url(r'^(?P<project_id>[-\w]+)/add_set/$', 'questionnaire_create' , name="project_questionnaire_create"),
我相信该解决方案涉及 Django ContentType框架,但我不确定通过 url 传递模型类的最佳方法。因此,如果要将 Question_set 保存到 Foo 模型而不是 Project。我将如何在 url 中识别模型类?