简体   繁体   English

使用 FormView 保存在 Django 表单中

[英]Saving in django forms using FormView

I'm creating a form that will change the state of reserve book, I have this我正在创建一个可以更改保留书状态的表单,我有这个

    class LibraryReserveForm(CrispyFormMixin, forms.Form):

          def __init__(self, *args, **kwargs):
              self.manager = kwargs.pop('manager')
              super(LibraryReserveForm, self).__init__(*args, **kwargs)

          def save(self):
              self.instance.reserve_status = 'approved'

              self.instance.save()

              return self.manager

models.py模型.py

    class ReservedBooks(TimeStampedModel):

        BOOK_RESERVE_STATUS = Choices(
             ('for_approval', "For Approval"),
             ('approve', "Approved"),
             ('cancelled', "Cancelled"),
             ('rejected', "Rejected")
        )

        reserve_status = models.CharField(
               _('Status'),
               max_length=32,
               choices=BOOK_RESERVE_STATUS,
               default='for_approval'
        )

    ...

view看法

    class LibraryReserveView(
          ProfileTypeRequiredMixin,
          MultiplePermissionsRequiredMixin,
          FormView,
    ):

    model = ReservedBooks
    template_name = 'library/reserved_list.html'
    form_class = LibraryReserveForm

    def get_form_kwargs(self):
        kwargs = super(LibraryReserveView, self).get_form_kwargs()

        kwargs.update({
            'manager': self.request.user.manager,
        })

        return kwargs

urls网址

    url(
        r'^reserve/(?P<pk>\d+)/$',
        views.LibraryReserveView.as_view(),
        name='reserved'
    ),

everytime I submit the button I print something in the save() method of the forms but its not printing something therefore that method is not called.每次我提交按钮时,我都会在表单的 save() 方法中打印一些东西,但它不打印一些东西,因此不会调用该方法。 How do you called the save method ?你如何调用保存方法? Thanks谢谢

A FormView does not handle saving the object. FormView不处理保存对象。 It simply calls form_valid that will redirect to the success_url .它只是简单地调用form_valid将重定向到success_url But an UpdateView adds boilerplate code to pass the instance to the form, and will save the form.但是UpdateView添加了样板代码以将实例传递给表单,并将保存表单。

You work with a Form , but a Form has no .instance attribute.您使用Form ,但Form没有.instance属性。 A ModelForm has, so it might be better to use a ModelForm here: ModelForm有,所以在这里使用ModelForm可能更好:

class LibraryReserveForm(CrispyFormMixin, forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.manager = kwargs.pop('manager')
        super(LibraryReserveForm, self).__init__(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.instance.reserve_status = 'approved'
        return super().save(*args, **kwargs)

Then we can make use of an UpdateView :然后我们可以使用UpdateView

from django.views.generic import UpdateView

class LibraryReserveView(
          ProfileTypeRequiredMixin,
          MultiplePermissionsRequiredMixin,
          UpdateView
    ):

    model = ReservedBooks
    template_name = 'library/reserved_list.html'
    form_class = LibraryReserveForm
    success_url = …

    def get_form_kwargs(self):
        kwargs = super(LibraryReserveView, self).get_form_kwargs()
        kwargs.update(
            manager=self.request.user.manager
        )
        return kwargs

You still need to specify the sucess_url here: the URL to which a successful POST request will redirect to implement the Post/Redirect/Get pattern [wiki] .您仍然需要在此处指定sucess_url :成功的 POST 请求将重定向到的 URL,以实现Post/Redirect/Get模式 [wiki]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM