Django FormView : distinguishing between create and update

标签 django django-generic-views

我有一个自定义 FormView 类的 mixin,如果保存成功,它只会添加一条成功消息,所以:

class MessagesMixin(object):

    def form_valid(self, form):
        response = super(MessagesMixin, self).form_valid(form)
        messages.add_message(self.request,
                             messages.SUCCESS,
                             'Successfully created %s' % form.instance)
        return response

如您所见,这仅真正涵盖了创作。如果实例已更新,消息仍将显示“已创建”。有没有办法区分 form_valid 方法中的创建/更新?

最佳答案

一种解决方案是在你的 mixin 中添加一个属性,然后在你的 Update 中设置它。和 Create意见。您可以定义静态属性或重载 get_form_valid_msg如果你需要一些动态的东西。未经测试的代码:

from django.core.exceptions import ImproperlyConfigured

class MessagesMixin(object): 
    @property
    def form_valid_msg(self):
        raise ImproperlyConfigured("you're missing the 'form_valid_msg' property")

    def get_form_valid_msg(self):
        return self.form_valid_msg

    def form_valid(self, form):
        response = super(MessagesMixin, self).form_valid(form)

        msg = 'Successfully {form_valid_msg} {form}'.format(
            form_valid_msg=self.get_form_valid_msg(),
            form=form.instance
        )

        messages.success(self.request, msg)

        return response

关于Django FormView : distinguishing between create and update,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17766056/

相关文章:

Django CreateView 字段标签

django - Django中的并发性能(apache2 prefork/mod_wsgi),我在做什么错?

python - 在 Django Facebook 中注销?

python - 通过 sendgrid-python API lib 将 django 对象上下文传递给 sendgrid 电子邮件

python - 将表单集保存在 UpdateView 中

python - 如何在应用程序的 urls.py 中设置通用 View ?

python - Django 教程 : Generic Views. 属性错误

Django:将过滤(和排序)添加到基于(通用)类的 ListView 的最佳方法?

python - DjangoCMS 教程 : Plugins 上的 NoReverseMatch 错误

django - 在sqlite中为条目保留一个id(pk)