0

我有允许动态创建表单的问卷调查应用程序。在我当前的系统中,我将它链接到一个项目。这是我的模型的一个例子。我想将问卷应用程序与我当前 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 中识别模型类?

4

1 回答 1

0

我认为问题可能出在您组织模型的方式上。我也会避免使用以结尾的型号名称,_set因为这可能会让人非常困惑。那么这个呢:

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from questionnaire.models import Questionnaire

#project.models
class Project(models.Model):
    name = models.CharField(max_length.....
    category = models.CharField(max_length
    questionnaires = generic.GenericRelation(Questionnaire)

#questionnaire.models
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Question(models.Model):
    question = models.CharField(max_length....
    question_type = models.IntegerField(choices=.....

class Questionnaire(models.Model):
    name = models.CharField(...)
    questions = models.ManyToManyField(Question)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey()

一旦您将问卷明确定义为自己的完整模型,创建 URL 就变得更加简单:

#questionnaire.urls
#pattern for question_set_create
url(r'^(?P<content_type>[-\w]+)/(?P<object_id>[-\w]+)/add_set/$', 'questionnaire_create' , name="questionnaire_create"),

其中 content_type 是内容类型的名称(例如“projects.project”或类似名称),object_id 是匹配记录的主键。

So the equivalent URL for creating a questionnaire for project id #1 would be /questionnaires/projects.project/1/add_set/

于 2011-01-25T07:11:20.623 回答