如何使用FormView引用新创建的对象

时间:2014-12-22 00:49:09

标签: django django-views

考虑我在下面覆盖的FormView。成功创建新的联盟记录后,如何引用该记录以便我可以将用户重定向到特定于该联盟的更一般的编辑页面?

class LeagueView(FormView):
    template_name = 'leagueapp/addleague.html'
    form_class = LeagueForm

    def form_valid():
        newleague = ??? #newly created league
        success_url = '/league/editleague/' + str(newleague.id)
        return HttpResponseRedirect(self.get_success_url())

1 个答案:

答案 0 :(得分:1)

这是非常简单的,给出了league名称空间中的网址,如

url(r'^league/editleague/(?P<id>\d+>)$', LeagueView.as_view(), name='edit')

您应该以这种方式编辑form_valid方法:

from django.shortcuts import redirect

class LeagueView(FormView):
    template_name = 'leagueapp/addleague.html'
    form_class = LeagueForm

    def form_valid(self, form):
        newleague = form.save()
        return redirect('league:edit', id=newleague.id)