表单提交后,在Django中重定向的最佳实践/帮助

时间:2016-11-03 20:51:09

标签: python django

Django noob在这里,不太了解这些概念,因此无法从StackOverflow的类似问题中获得任何帮助。

我有一个只有一个下拉列表的表单,如果按下提交,则下拉列表的值应转发到下一页。因此,根据下拉列表自定义内容。

如何使用参数将帖子重定向到下一页?是否正确使用" HttpResponseRedirect(反向"?

views.py

def appStart(request, institution):
    #so something with institution
    return render(request, 'application/SectionStart.html', {'content':{'if you would like to contact me emial','email@email.com'}})

def ReviewMyView(request):
    form_class = ApplicationSelectInstituation
    if request.method == 'POST':
         form = form_class(data=request.POST)
         if form.is_valid():
             for field, value in form.cleaned_data.items():
                 return HttpResponseRedirect(reverse('appStart', args=(value,)))
                 #return HttpResponseRedirect(reverse('view_blog', args=(), kwargs={'institution': value}))
                 #return HttpResponseRedirect(reverse('appStart'), {'institution': value})
                 #return HttpResponseRedirect(reverse('appStart'), institution=value)

    return render(request, 'application/appmyreview.html', {
        'form': form_class
    })

urls.py

urlpatterns = [
url(r'^xxx/(?P<institution>\d+)$', appStart, name='appStart'),
url(r'^myapp$', ReviewMyView, name='review'),
]

更新

感谢您的回答,我认为我需要阅读Django基础知识,因为我没有得到它。

def my_awesome_django_view(request):
    form_class = ApplicationSelectInstituation

    if request.method == "POST":
        form = ApplicationSelectInstituation(data=request.POST)
        if form.is_valid():
            content_data = form.cleaned_data.get('institution_name').id
            #Try 1 - page just refreshes
            #redirect("nextapppage/"+str(content_data))
            #Try 2 - Reverse for 'next_view' with arguments '()' and keyword arguments '{'institution_id': 3}' not found. 0 pattern(s) tried: []
            #return HttpResponseRedirect(reverse('next_view',kwargs={'institution_id': content_data}))
            #Try 3 - Reverse for 'next_view' with arguments '(3,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []
            return HttpResponseRedirect(reverse('next_view', args=[content_data]))

    return render(request, 'application/appmyreview.html', {
        'form': form_class
    })

def the_next_view(request, *args, **kwargs):
    print("I got to: the_next_view")
    return render(request, 'application/SectionStart.html', {'content':{'if you would like to contact me emial','email@email.com'}})

urls.py

urlpatterns = [
url(r'^myapp$', my_awesome_django_view, name='myapp'),
url(r'^nextapppage/(?P<institution_id>\d+)/$', the_next_view, name='the_next_view'),

3 个答案:

答案 0 :(得分:0)

你可能应该使用HttpResponseRedirect与反向一致。

您可以提供与args参数反转的参数。所以在你看来:

def my_awesome_django_view(request):
    # some get method stuff
    if request.method == "POST":
        form = MyForm(data=request.POST)
        if form.is_valid():
            content_data = form.cleaned_data.get('my_field')
            return HttpResponseRedirect(reverse('next_view', args=[content_data]))

在下一个视图中:

def the_next_view(request, *args, **kwargs):
    content = content_getter(*args)
    return HttpResponse(content)

在urlconf中你不会在正则表达式中使用命名参数但是我会使用命名参数来明确和明确,因此在2个月内,当你试图找出你写这个的原因时你#&# 39;能给自己一些面包屑(很多次学到了很多次)。

对于kwargs你只需要传递它:

reverse('my_view_name', kwargs={'my_kwarg': value})

为了完整性:

urlpatterns = [
    url(r'^xxx/(?P<institution>[\d]+)$', the_next_view, name='appStart'),
    url(r'^myapp$', my_awesome_django_view, name='review'),
]

另请注意,我已经更改了urlconf中的正则表达式。

答案 1 :(得分:0)

您是否考虑过使用class-based views?它们使用起来非常简单,大部分基本功能都已经为您完成,并且包含直观的名称和精美的文档。

from django.views.generic.edit import FormView

class MyFormView(FormView):
    template_name = 'my_template.html'
    form_class = MyForm

    def form_valid(self, form):
        # on successful form submit
        self.next_url = reverse('appStart', args=[form.some_value])
        return super().form_valid(form)

    def get_success_url(self):
        return self.next_url
urls.py

中的

url(r'^myapp$', MyFormView.as_view(), name='review'),

答案 2 :(得分:0)

如果您的视图需要引导另一个视图,然后该视图会向浏览器提供响应,为什么不使用快捷方式redirect

from django.shortcuts import redirect

def ReviewMyView(requst):
    if request.method == 'POST':
        # do stuff...
        redrect(appStart, form.cleaned_data[?])

您可以传递下一个视图所需的任何参数。