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?
ModelForm
? In that case you better useModelFormView
, since this offers more convenience for this. – SaturninasaturnineForm
to aModelForm
so to speak, but you can letSomeForm
use theModelForm
subclass (in case it directly maps on a single model). – Saturninasaturnine