0

I want to save the data in the form and go back to previous page when I click on 'Add' button. It's showing some errors. Can anyone suggest the correct way to do it?

template.html

  <div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title">Add your own Category </h3>
  </div>
  <div class="panel-body">
    <form method="POST" class="post-form">
      {% csrf_token %}
      {{ form.as_p }}

                    </div>
                      </div>
                    </div>
        <input type="hidden" name="next" value="{{ request.path }}">
       <button type="submit" class="save btn btn-default" >Add</button>
    </form>

views.py

class CustomCategory(LoginRequiredMixin,CreateView):
    model = Category

   form_class = CategoryForm

   def form_valid(self, form):
    obj = form.save(commit=False)

   def category(request):
    next = request.POST.get('next', '/')
    return render (request,HttpResponseRedirect(next))
user
  • 187
  • 1
  • 2
  • 12

1 Answers1

0

Instead of adding the redirect as an element of the form, why don't you use the success_url field on the view, or if the URL you need to go to depends on an object, use the get_success_url method on the view?

https://docs.djangoproject.com/en/2.0/ref/class-based-views/mixins-editing/

  • can you tell me how can I do that with success_url ? I am new to django – user May 23 '18 at 17:54
  • You need to add in: from django.urls import reverse (put this at the beginning) Then, in your view, add in success_url=reverse('URL') (make sure to replace URL with the absolute URL you are trying to go to (in the Django app:name format, not http://example.com)). Also, I think both your methods might be unnecessary. The first one doesn't actually change the database (not sure if that's what you want), and the second doesn't really seem to do anything. – Alexander Skvortsov May 23 '18 at 18:36