【问题标题】:How to redirect to same page with get absolute url如何使用获取绝对网址重定向到同一页面
【发布时间】:2021-04-29 17:24:46
【问题描述】:

我的详细信息和创建视图正在工作,但在帖子下添加评论后我无法重定向到同一页面...

我想从我的 CommentForm 中删除“帖子”字段,以便我将评论保存到帖子对象,而无需用户选择要保存到的帖子 // 我为评论的作者做了同样的事情,但不能为帖子本身做同样的事情

我的观点

class PostDetailView(DetailView):
    model = Post
    template_name='blog/post_detail.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        comments = Comment.objects.filter(post=self.object)
        context['comments'] = comments
        context['form'] = AddCommentForm()
        return context
    

class CommentCreateView(CreateView):
    model = Comment
    fields = ['content','post']
    template_name = 'blog/post_detail.html'
    
    def form_valid(self, form): 
        form.instance.author = self.request.user
        return super().form_valid(form)

我的模型

class Post(models.Model):

    options = (
        ('draft', 'Draft'),
        ('published', 'Published')
    )

    title = models.CharField(max_length=250)
    slug =  models.SlugField(max_length=250, unique_for_date='publish_date')
    publish_date = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
    content = models.TextField()
    status = models.CharField(max_length=10, choices=options, default='draft')
  
    class Meta:
        ordering = ('-publish_date',)

    def __str__(self):
        return self.title

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.TextField()
    publish_date = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('-publish_date',)

    def __str__(self):
        return f'Comment By {self.author}/{self.post}'

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk':self.post.pk})

我的表格



class AddCommentForm(forms.ModelForm):
    content = forms.CharField(label ="", widget = forms.Textarea( 
    attrs ={ 
        'class':'form-control', 
        'placeholder':'Comment here !', 
        'rows':4, 
        'cols':50
    })) 

    class Meta: 
        model = Comment 
        fields =['content','post']

html表单

            <form action="{% url 'blog:comment-update' object.id%}" method="POST">
              <div class="col-12">
                <hr>
                {% with comments.count as total_comments %}
                  <legend class="border-bottom mb-4">{{total_comments }} comment{{total_comments|pluralize }}</legend>
                {% endwith %}
                {% for c in comments%}
                  <div class ="col-md-12 mb-1rem" >
                    <p class="mb-0"><strong>{{c.author}}:</strong> {{c.content}}</p>
                    <small class="text-muted">{{ c.publish_date|date:'f A, Y'}}</small>
                  </div>
                  <br>
               {% endfor %}
              </div>
              <hr>    
              {% csrf_token %}
              <fieldset class="form-group">
                  <legend class="border-bottom mb-4">New Comment</legend>
                  {{ form|crispy }}
              </fieldset>
              <div class="form-group">
                  <button class="btn btn-dark btn-lg mt-1" type="submit">Publish</button>
              </div>
            </form>

网址

urlpatterns = [
    path('', views.PostListView.as_view(), name='blog-home'),
    path('blog/<int:pk>/', views.PostDetailView.as_view(), name='post-detail'),
    path('blog/<int:pk>/update', views.CommentCreateView.as_view() , name='comment-update'),
    ]

【问题讨论】:

    标签: django django-models django-views django-forms django-templates


    【解决方案1】:

    您需要:

    • 将帖子的 PK 传递给 CommentCreateView(通过 URL),并使用它在 form_valid() 方法中更新评论
    • 从表单定义的字段列表中删除“post”
    • 为您的 form_valid() 方法添加一个重定向,该重定向返回到 get_absolute_url() 中定义的 Post 的 URL

    假设您确实将 Post 的 PK 传递给 URL,在 form_valid() 中添加以下内容:

    post = Post.objects.get(pk=self.kwargs.get('pk'))
    self.object = form.save(commit=False)
    self.object.post = post
    self.object.save()
    return redirect(self.object.get_absolute_url())
    

    【讨论】:

    • 请问我如何重定向到同一页面
    • 您希望重定向到哪个 URL?您从哪个页面发布到 CommentCreateView?我编辑了我的答案几次,所以你可能没有看到我稍后添加的重定向。
    • 我的 CommentForm 在页面中(post-detail),所以当我提交评论时,我希望它重定向到同一页面(post-detail),即 DetailView 页面——(我的 CreateView 是也在 DetailView 页面中)但在 url 中它有不同的 url
    • 重定向代码给了我一个错误:Reverse for 'post-detail' not found。 'post-detail' 不是有效的视图函数或模式名称。
    猜你喜欢
    • 2021-03-20
    • 1970-01-01
    • 2012-03-31
    • 2017-11-18
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多