Django:在覆盖模型的保存方法的同时访问会话变量 [英] Django: accessing session variable while overriding model's save method

查看:119
本文介绍了Django:在覆盖模型的保存方法的同时访问会话变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法访问会话变量,而覆盖任何模型保存方法

Is there any way to access sessions variables while overriding any models save method

class Blog(models.Model):
  name = models.CharField(max_length=100)
  tagline = models.TextField()

  def save(self, *args, **kwargs):
    //Code for accessing session variable
    super(Blog, self).save(*args, **kwargs)

谢谢,

推荐答案

不直接

可以在保存方法中添加一个额外的参数,并在调用超级保存之前弹出它:

you could add an extra argument to the save method and pop it off before calling the super save:

def save(self, *args, **kwargs):
    request = kwargs.pop('request')

view...:
    instance.save(request=request)

但是
如果您保存表单可能会更好地使用

But if you are saving a form it may be better to use

view...:
    instance = form.save(commit=False)
    # do some logic
    instance.save()

这篇关于Django:在覆盖模型的保存方法的同时访问会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆