【问题标题】:Passing the pk from url to CreateView form_valid将 pk 从 url 传递到 CreateView form_valid
【发布时间】:2019-12-19 06:25:16
【问题描述】:

我想将其他模型的 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)

有什么建议吗?

编辑//

【问题讨论】:

    标签: python django django-forms django-views


    【解决方案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)
    

    【讨论】:

    • 我改了,现在报错:Reverse for 'comment-create' with no arguments not found.
    • 你在哪里开始反向?你能分享完整的错误堆栈跟踪吗?
    • Exception Type: NoReverseMatch Exception Value: Reverse for 'comment-create' with no arguments not found. 1 pattern(s) tried: ['comment/(?P&lt;scenario_id&gt;[0-9]+)/$']
    • 哦,我找到了! &lt;form method="POST" action="{% url 'comment-create' %}" onsubmit="setTimeout(function(){window.location.reload();},10)"&gt; &lt;div class="center"&gt;&lt;h5&gt;Add:&lt;/h5&gt;&lt;/div&gt; {% csrf_token %} {{ newComment }} &lt;div class="center"&gt; &lt;button class="btn waves-effect waves-light" type="submit" value="Submit"&gt;Publish&lt;/button&gt; &lt;/div&gt; &lt;/form&gt;是这个原因吗?我应该改变它吗?
    • 对不起,我的错。根据我的最后评论删除更改。你能在模板中试试这个网址吗:{% url 'comment-create' scenario.pk %}
    猜你喜欢
    • 2019-09-22
    • 1970-01-01
    • 2020-03-26
    • 2018-04-07
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 2014-12-12
    相关资源
    最近更新 更多