Django FormView在success_url中传递pk

时间:2018-07-01 12:24:02

标签: django django-forms django-views django-class-based-views

假设我具有以下FormView,并且我想在提交表单后将item.pk传递给其他视图。我想我必须编辑get_success_url(),但我什至无法弄清楚如何从item.pk获取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?

1 个答案:

答案 0 :(得分:1)

您可以像下面这样

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


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