Ben
Ben

Reputation: 21625

How to reference the newly created object using FormView

Consider the FormView that I'm overriding, below. Upon successful creation of a new League record, how do I reference that record so that I can redirect the user to a more general edit page specific to that League?

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())

Upvotes: 0

Views: 468

Answers (1)

DRC
DRC

Reputation: 5048

this is really straight forward, given an url in the league namespace like

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

you should edit the form_valid method in this way:

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)

Upvotes: 1

Related Questions