Django:在创建新对象时,如何将URL中的Object_PK与Foreign_Key关系字段相关联?

时间:2016-10-06 17:15:20

标签: python django

我正在构建一个FAQ系统。模型从主题扩展 - >部分 - >文章。在创建新文章时,用户将选择一个主题,然后选择一个部分,然后选择创建文章按钮。

网址看起来像//mysite.org/Topic_PK/Section_PK/Article_Create

在Django中它应该是这样的:

url(r'^ironfaq/(?P<pk>\d+)/(?P<pk>\d+)/article$', ArticleCreateView.as_view(), name=’article-create’)

我想要做的是在用户提交文章时将Section_PK与文章相关联。我在URL中有Section_PK,我需要帮助来弄清楚如何使用它来执行此操作。

或者使用此设置,我可以使用文章模型中的Section_FK选择选项来呈现表单。如果我在渲染模板时创建文章,如果我可以通过form.py中的主题限制部分选项,这也可以满足我的需求

网址看起来像//mysite.org/Topic_PK/article/create

在Django中,网址应如下所示:

url(r'^ironfaq/(?P<pk>\d+)/article/create$', ArticleCreateView.as_view(), name=’article-create’)

这两种方法都需要将主题或部分PK传递给视图或通过URL形成。如果有更好的方法,我愿意接受其他建议。

在Django中我有以下模型

class Topic(Audit):
    name = models.CharField(max_length=255)
    sort = models.SmallIntegerField()
    slug = models.SlugField()

    class Meta:
        verbose_name_plural = "topics"

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return ('faq-topic-detail',(), {'slug': self.slug})

class Section(Audit):
    name = models.CharField(max_length=255)
    sort = models.SmallIntegerField()
    slug = models.SlugField()
    topic = models.ForeignKey(Topic,on_delete=models.CASCADE)

    class Meta:
        verbose_name_plural = "sections"

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return ('faq-section-detail',(), {'topic__slug': self.topic.slug,
            'slug': self.slug})

class Article(Audit):
    title = models.CharField(max_length=255)
    sort = models.SmallIntegerField()
    slug = models.SlugField()
    section = models.ForeignKey(Section,on_delete=models.CASCADE)
    answer = models.TextField()
    vote_up = models.IntegerField()
    vote_down = models.IntegerField()
    view_count = models.IntegerField(default=0)

    class Meta:
        verbose_name_plural = "articles"

    def __str__(self):
        return self.title

    def total_votes(self):
        return self.vote_up + self.vote_down

    def percent_yes(self):
        return (float(self.vote_up) / self.total_votes()) * 100

    def get_absolute_url(self):
        return ('faq-article-detail',(), {'topic__slug': self.section.topic.slug,
            'section__slug': self.section.slug, 'slug': self.slug})

Mysite Forms

class CreateArticleForm(forms.ModelForm):

    class Meta:
        model = Article
        widgets = {
            'answer': forms.Textarea(attrs={'data-provide': 'markdown', 'data-iconlibrary': 'fa'}),
        }
        fields = ('title','section','answer')

Mysite Views

class TopicCreateView(CreateView):
    model = Topic
    fields = ['name']
    template_name = "faq/form_create.html"
    success_url = "/ironfaq"

    def form_valid(self, form):
        topic = form.save(commit=False)
        activity_user = self.request.user.username
        activity_date = datetime.datetime.now()
        topic.save()
        return super(TopicCreateView,self).form_valid(form)

class SectionCreateView(CreateView):
    model = Section
    fields = ['name', 'topic']
    template_name = "faq/form_create.html"

    def form_valid(self, form):
        section = form.save(commit=False)
        activity_user = self.request.user.username
        activity_date = datetime.datetime.now()
        section.save()
        self.success_url = "/ironfaq/%s/%s" % (section.topic.slug,section.slug)
        return super(SectionCreateView,self).form_valid(form)

class ArticleCreateView(CreateView):
    model = Article
    form_class = CreateArticleForm
    template_name = "faq/form_create.html"

    def form_valid(self, form):
        article = form.save(commit=False)
        activity_user = self.request.user.username
        activity_date = datetime.datetime.now()
        article.save()
        self.success_url = "/ironfaq/%s/%s/%s" % (article.section.topic.slug,article.section.slug,article.slug)
        return super(ArticleCreateView,self).form_valid(form)

1 个答案:

答案 0 :(得分:0)

假设你有这个网址

for B_card=1:size(GroupA,2)-1
  for C_card=(B_card+1):size(GroupA,2)
    if strcmp(GroupA(B_card).h,GroupA(C_card).h)==1
      warning('The h is same in',GroupA(B_card).ID,'&',GroupA(C_card).ID);
    end
  end
end

url(r'^ironfaq/(?P<topic_pk>\d+)/article/create$', ArticleCreateView.as_view(), name=’article-create’) 将成为您想要与您的文章相关联的主题的pk。

然后你只需要在视图中检索它。这就是这样做的

topic_pk

所有网址参数都存储在class ArticleCreateView(CreateView): model = Article form_class = CreateArticleForm template_name = "faq/form_create.html" def form_valid(self, form): article = form.save(commit=False) # what are this variables for? activity_user = self.request.user.username activity_date = datetime.datetime.now() # here we are getting 'topic_pk' from self.kwargs article.topic_id = self.kwargs['topic_pk'] article.save() self.success_url = "/ironfaq/%s/%s/%s" % (article.section.topic.slug,article.section.slug,article.slug) return super(ArticleCreateView,self).form_valid(form) self.args中。我们的self.kwargs是命名参数,这就是为什么我们可以通过topic_pk

来获取它

但请确保在将self.kwargs['topic_pk']分配给Topic之前验证Article是否存在<{1}}