简体   繁体   English

Django重定向回表单发布的上一页

[英]Django redirect back to previous page on form post

I'm trying to have a form post redirect back to the page it was posted from. 我正在尝试将表单发布重定向到它发布的页面。 So my app has a detail page that displays information about a place, /arena/123, and on the same page there is a form that a user can enter some comments or ratings about the current place they are looking at. 因此,我的应用程序有一个详细页面,该页面显示有关地点/ arena / 123的信息,并且在同一页面上,用户可以输入一种形式来输入有关他们正在查看的当前地点的评论或评分。 These are my view functions. 这些是我的视图功能。

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

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

def rate(request):
    if request.method == 'POST':
        form = RatingForm(request.POST)
        if form.is_valid():
            # post was valid. go back to page and display data
            return DetailView.as_view()(request(), form=RatingForm)
        else:
            # post was unsuccessful. go back to the page and display errors
            print form.errors
            return DetailView.as_view()(request(), form=form)

and my template 和我的模板

{% 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/rate/" method="post">
        {% csrf_token %}
        {{ form }}
    <input type="submit" value="Submit" />
    </form>

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

So what I'd like to do is after a user submits the form on the page I'd like to go back to the same detail page I was on and either have the data that user posted there shown in the comments section if it was successful or redirect back to the same page but with the form errors if it was unsuccessful. 所以我想做的是,当用户在页面上提交表单后,我想返回到我所在的同一详细信息页面,并且如果有用户在其中张贴的数据,成功或重定向到同一页面,但如果不成功,则会出现表格错误。 My problem is right now I don't know how to retain the url and form errors to display the detail page again. 我的问题是现在不知道如何保留网址和表单错误以再次显示详细信息页面。 I don't think I can use return DetailView.as_view()(context(), form=form) because my DetailView doesn't have a post so I get a 405. Every example I see doesn't cover redirecting back to the same page. 我不认为我可以使用return DetailView.as_view()(context(), form=form)因为我的DetailView没有帖子,所以我得到405。我看到的每个示例都不涵盖重定向回同一页。 They usually just show a HttpResponseRedirect(/thanks) or something similar. 它们通常只显示HttpResponseRedirect(/thanks)或类似内容。

Also note. 另请注意。 I don't want to post to /arena/123 because eventually that will be another feature to update information about the place so I didn't want to put the comments post on that url. 我不想发布到/ arena / 123,因为最终这将是更新有关该地点的信息的另一个功能,因此我不想将评论发布到该url上。

So I dug into some more Django examples and stumbled across SingleObjectMixin . 因此,我深入研究了一些Django示例,并偶然发现了SingleObjectMixin This combined with a FormView seems to be what I want. 这与FormView结合似乎是我想要的。 The Django docs had an example that was 99.9 percent what I wanted here . Django文档有,这是99.9%的什么我想要的例子在这里 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 添加了使用/ 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 并修改了我的模板以将对象的id传递给表单发布操作中的路线

{% 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. 现在在发生错误时保留上下文,并且SingleObjectMixin / FormView组合使我停留在同一页面上以显示表单错误,并在成功发布get_success_url其重定向到我想使用get_success_url再次使用新信息加载页面的详细信息页面那被张贴了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM