将pk从网址传递到CreateView form_valid

时间:2019-12-19 06:25:16

标签: python django django-forms django-views

我想将其他模型的pk从URL传递到我的CreateView表单。怎么做?你可以帮帮我吗?当我传递特定的id时,它可以工作,但是我想从URL自动获取pk。 我的views.py

class ScenarioDetailView(LoginRequiredMixin, DetailView):
    model = Scenario

class CommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    fields = [
        'commentText'
    ]

    def form_valid(self, form):
        form.instance.commentAuthor = self.request.user
        form.instance.commentDate = datetime.now()
        form.instance.commentScenario = Scenario.objects.get(pk=1) #there is my problem
        return super().form_valid(form)

我的url.py

path('scenario/<int:pk>/', ScenarioDetailView.as_view(), name='scenario-detail'),

也是我的模特:

class Comment(models.Model):
    commentText = models.CharField(max_length=256)
    commentScenario = models.ForeignKey(Scenario, on_delete=models.CASCADE)
    commentAuthor = models.ForeignKey(User, on_delete=models.CASCADE)
    commentDate = models.DateTimeField(default=timezone.now)

有什么建议吗?

编辑// enter image description here

1 个答案:

答案 0 :(得分:1)

您可以从self.kwargs字典中获取值。例如:

# url
path('comment/<int:scenario_id>/', CommentCreateView.as_view(), name='comment-create'),

# view
class CommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    fields = [
        'commentText'
    ]
    def form_valid(self, form):
            form.instance.commentAuthor = self.request.user
            form.instance.commentDate = datetime.now()
            form.instance.commentScenario = Scenario.objects.get(pk=self.kwargs.get('scenario_id')) #there is my problem
            return super().form_valid(form)