0

I have a PostForm model form to create posts for my blog app. Now the user has two options after filling the post form he/she can publish it immediately or can put it into the drafts for later publishing. when published the user will be redirected to that post's detail view but when drafted it will redirect to user's draft list view. I don't want to create a detail view for the draft posts.

But I am not able to implement how can I redirect a user to two different views with the two different submit option (Publish and draft) in the form.

create view

    model = Post
    template_name = 'blog/post_form.html'
    form_class = PostForm

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = 'Create'
        return context

    def form_valid(self, form):
        form.instance.author = self.request.user
        form.save()
        return super().form_valid(form)

post_form.html

    model = Post
    template_name = 'blog/post_form.html'
    form_class = PostForm

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = 'Create'
        return context

    def form_valid(self, form):
        form.instance.author = self.request.user
        form.save()
        return super().form_valid(form)
Gaurav Sahu
  • 181
  • 3
  • 11

1 Answers1

1

You can try like this:

First add two different buttons in your form which has different names(ie draft and publish):

<form action="" method="post">
    {{ form }}
    <input type="submit" name="draft" value="Draft" />
    <input type="submit" name="publish" value="Publish" />
</form>

Then override the get_success_url() method inside your create view:

def get_success_url(self):
   if 'draft' in self.request.POST:
       return reverse('draft-url')
   return reverse('publish-url')

Update

Lets say your Blog model has a get_absolute_url method which redirects to published blog. Then you can use it like this:

# model
class Blog(models.Model):
   ...
   def get_absolute_url(self):
       return reverse('blog:publish_post', slug=self.slug)

# view
def get_success_url(self):
   if 'draft' in self.request.POST:
       return redirect('draft-url')
   return super().get_success_url()
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • But I am getting the "MultiValueDictKeyError" error while passing the slug field for post publish url. `def get_success_url(self): if 'publish' in self.request.POST: return redirect('blog:publish_post', slug=self.request.POST['slug']) return redirect('blog:drafts_posts') ` – Gaurav Sahu Jun 25 '19 at 04:44
  • @GauravSahu please see the update section of the answer – ruddra Jun 25 '19 at 05:27
  • get_success_url needs to return a URL, so it should not call redirect itself. – Daniel Roseman Jun 25 '19 at 07:08
  • @DanielRoseman yes, you are right, my bad. I have updated the answer. thanks. – ruddra Jun 25 '19 at 07:16