[Fixed]-Django redirect back to previous page on form post

1๐Ÿ‘

โœ…

So I dug into some more Django examples and stumbled across SingleObjectMixin. This combined with a FormView seems to be what I want. The Django docs had an example that was 99.9 percent what I wanted here. Just be sure to read down to the better solution section.

I changed my views to this

class DetailView(LoginRequiredMixin, generic.DetailView):
    model = Arena
    template_name = 'arenas/detail.html'

    def get_context_data(self, **kwargs):
        print kwargs
        context = super(DetailView, self).get_context_data(**kwargs)
        context['form'] = RatingForm
        return context


class RatingView(LoginRequiredMixin, detail.SingleObjectMixin, generic.FormView):
    model = Arena
    template_name = 'arenas/detail.html'
    form_class = RatingForm

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        return super(RatingView, self).post(request, *args, **kwargs)

    def get_success_url(self):
        print "successfully posted"
        return reverse('arenas:detail', kwargs={'pk': self.object.pk})

Added a route for posting the form with /rate

urlpatterns = patterns('',
                       url(r'^$', views.IndexView.as_view(), name='index'),
                       url(r'^(?P<pk>\d+)/$',
                           views.DetailView.as_view(), name='detail'),
                       url(r'^(?P<pk>\d+)/rate/$', views.RatingView.as_view(), name='rate')
                       )

and modified my template a bit to pass the id of the object to my route in the form post action

{% extends "base.html" %}
{% block content %}
    <h1>{{ arena.address }}</h1>
    <h1>{{ arena.address_2 }}</h1>
    <h1>{{ arena.phone }}</h1>

    {% if form.errors %}
        {% for field in form %}
            {% for error in field.errors %}
                <div class="alert alert-error">
                    <strong>{{ error|escape }}</strong>
                </div>
            {% endfor %}
        {% endfor %}
        {% for error in form.non_field_errors %}
            <div class="alert alert-error">
                <strong>{{ error|escape }}</strong>
            </div>
        {% endfor %}
    {% endif %}
    <form action="/arenas/{{ arena.id }}/rate/" method="post">
        {% csrf_token %}
        {{ form }}
    <input type="submit" value="Submit" />
    </form>

    <div>
        {{comments}}
    </div>
{% endblock %}

Now on an error the context is kept and the SingleObjectMixin/FormView combination keeps me on the same page to display the form errors and on a successful post it redirects to the detail page I want using the get_success_url to load the page again with the new information that was posted.

๐Ÿ‘คThrowsException

Leave a comment