如何使用GET查询中的参数创建外键对象

时间:2019-06-18 07:13:15

标签: python-3.x django-2.1

我需要为该文章创建一个关联的投票模型,以便注册用户不能为一篇文章进行两次投票。因此,我使用get_or_create()并且不了解如何从kwargs中提取文章

class CollDetailView(DetailView):
model = Art
template_name = 'art_detail.html'
queryset = Art.objects.all_with_related_persons_and_score()

def get_context_data(self, **kwargs):
    ctx = super().get_context_data()
    vote = Art.objects.all_with_related_persons_and_score()
    #returns the number of created objects of votes
    if self.request.user.is_authenticated:
        voted = Vote.objects.get_or_create(
            author_id=self.request.user,
            art_id=self.object
        )
        if not voted:
            vote_form_url = reverse(
                'vote',
                kwargs={'art_id': self.object.slug}
            )

            ctx['vote_form_url'] = vote_form_url
    ctx['votes'] = vote
    return ctx

如何更正确地编写createview

class Create_Vote(CreateView):
model = Vote
template_name = 'art_detail.html'

def form_valid(self, form):
    model = form.save(commit=False)
    model.author_id = self.request.user
    model.art_id = kwargs['art_id']#??????????????
    model.save()

    return HttpResponseRedirect(self.get_success_url())

def get_success_url(self):
    return reverse('art_detail')

参考用户和文章,语音模型是最常见的。

0 个答案:

没有答案