Search code examples
pythondjangourlargs

How to feed success url with pk from saved model?


I create a new model with the CompanyCreateView. After saving it with f.save(), I want the browser to load the success url

    url(r'^comp/(?P<pk>\w+)/$', CompanyDetailView.as_view(), name="profile"),

Here my CreateView.

class CompanyCreateView(CreateView):
    model = Company
    form_class = CompanyForm
    success_url = "/comp/???pk???"

    def form_valid(self, form):
        f = form.save(commit=False)
        f.submitter_id = 99 # dont know how to remove the submitter, its not set in the model
        f.save()

        return super(CreateView, self).form_valid(form)

    def get_success_url(self, **kwargs):
        return reverse("profile", kwargs={'pk': self.request.pk})

How can I use args arguments to return pk?


Solution

  • def get_success_url(self, **kwargs):
        # obj = form.instance or self.object
        return reverse("profile", kwargs={'pk': self.object.pk})
    

    You expect a primary key on the request object, which makes no sense. The instance (self.object) is where you should retrieve the primary key from.