【问题标题】:How to do a POST request in a DetailView如何在 DetailView 中执行 POST 请求
【发布时间】:2021-04-28 20:57:48
【问题描述】:

我正在关注该项目的教程,但它是在功能视图上完成的,我试图在基于类的视图上完成

我得到一个(视图 blog.views.PostDetailView 没有返回 HttpResponse 对象。它返回 None 而是。)错误,但现在我不关心...因为数据(新 cmets)没有得到保存 那么如何将它们与发布请求一起保存并重定向到 DetailView 的同一页面

我的网址

app_name = 'blog'

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

我的模型

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

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'slug': self.slug})
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}'

我的表格

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']

我的观点

class PostDetailView( DetailView):
    model = Post
    context_object_name = '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

    def post(self, request, *args, **kwargs):
        pass

    def form_valid(self, form):
        form.instance.author = self.post.author
        user_comment.post = self.post
        user_comment.save()
        return super().form_valid(form)

html

            <form 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>

【问题讨论】:

  • 使用UpdateView
  • 不只是更新现有的 cmets 而不是创建新的 cmets

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


【解决方案1】:

DetailView 没有 form_valid 方法。 它只显示模型的对象。

表单处理在 GenericEdit View 类中。

有很多方法,但是... 在此代码中,您可以创建一个 GenericEdit 视图(CreateView 或 UpdateView)url,在那里处理表单(form_valid),然后
success_url = reverse_lazy('form:detail') # 在 GenericEdit 视图类
返回模板。

总结一下,

  1. 在 urls.py 中添加路径 像这样...?

path('blog/&lt;slug:slug&gt;/update', views.PostUpdateView.as_view(), name='post-update'),

  1. 在表单操作中添加更新或创建 url。 前任。 ☞action="{% url 'blog:post-update' %}"

  2. 制作 GenericEdit 视图类☞ views.PostUpdateView

ps.你也可以使用forms.py

"""
在django中使用Class Base View时,推荐参考本站。 https://ccbv.co.uk/

并且, DetailView 参考在这里 https://ccbv.co.uk/projects/Django/3.0/django.views.generic.detail/DetailView/
"""

【讨论】:

  • 我仍然不知道如何设置更新视图
  • UpdateView 需要这样的模型和字段.. class CommentUpdateView(UpdateView): model = models.Comment fields = [ 'username','comment' ] 文档在这里docs.djangoproject.com/en/3.1/ref/class-based-views/…
  • 谢谢,我是在 createview 上完成的。更新只是更新现有的 cmets
猜你喜欢
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 2014-07-26
  • 1970-01-01
  • 2011-07-29
  • 1970-01-01
  • 2019-10-18
相关资源
最近更新 更多