djangodjango-formsdjango-viewsdjango-class-based-views

Django FormView pass pk in success_url


Assuming I have the following FormView and i want to pass the item.pk to some other view after the form is submitted. I guess i have to edit get_success_url() but i can't even figure out how to get item.pk from form_valid():

models.py

from django.db import models

class Book(models.Model):
    field1 = models.CharField(max_length=32)
    field2 = models.CharField(max_length=32)
    field3 = models.CharField(max_length=32)

    def __str__(self):
        return self.field1

forms.py

from django import forms
from .models import Book

class SomeForm(forms.ModelForm):

    field_order = ['field3', 'field2', 'field1']

    class Meta:
        model = Book
        fields = ['field1', 'field2', 'field3']

views.py

from django.shortcuts import render
from django.views.generic.edit import FormView
from .forms import SomeForm

class SomeView(FormView):
    form_class = SomeForm
    template_name = 'appname/form.html'
    success_url = reverse_lazy('somewhere')


    def form_valid(self, form):

        # save in Database
        item = form.save()

        # item.pk stores the saved pk 

        return super().form_valid(form)

    def get_success_url(self)
         # how can i get item.pk from form_valid() here and pass it to another view?

Solution

  • You can do like below

    class SomeView(FormView):
        form_class = SomeForm
        template_name = 'appname/form.html'    
    
        def form_valid(self, form):
            item = form.save()
            self.pk = item.pk
            return super(SomeView, self).form_valid(form)
    
        def get_success_url(self):
             #print(self.pk)
             return reverse('some_url', kwargs={'pk': self.pk})