Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

django - How to redirect to same page with get absolute url

My Detail and Create Views are working but i cant redirect to the same page after adding a commment under the post ...

and i want to remove the 'post' field from my CommentForm so that i save the comment to a post object without the user choosing which post to save to // i did the same thing for the author of the comment but cant do it for the post itself

my views

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)

my models

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})

my form



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

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

urls

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

question from:https://stackoverflow.com/questions/65892682/how-to-redirect-to-same-page-with-get-absolute-url

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You will need to:

  • Pass the PK of the post, to the CommentCreateView (via the URL), and use this to update the comment in the form_valid() method
  • Remove 'post' from the list of fields in your form definition
  • Add a redirect to your form_valid() method, that goes back to the Post's URL as defined in get_absolute_url()

Assuming that you are indeed passing the PK of the Post, to the URL, add the following inside 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())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...