Django FormView:区分创建和更新

时间:2013-07-20 19:47:58

标签: 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方法中的创建/更新?

1 个答案:

答案 0 :(得分:5)

一种解决方案是在mixin中添加一个属性,然后在UpdateCreate视图中进行设置。如果需要动态,可以定义静态属性或重载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