V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
python30
V2EX  ›  Python

问一个 django 编辑信息扣除相应用户积分的问题

  •  
  •   python30 · 8 天前 · 521 次点击

    问一个 django 编辑信息扣除相应用户积分的问题

    class EditTopicForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            
            self.user = kwargs.pop('user', None)
            self.topic_id = kwargs.pop('topic_id', None)
            #以上两条语句取不到相应的值
            super(EditTopicForm, self).__init__(*args, **kwargs)
            
        class Meta:
            model = Topic
            #fields = "__all__"
            fields = ['title', 'body', 'ys_t','is_cuti']
        def save(self, commit=True):
            inst = super(EditTopicForm, self).save()        
            if inst.is_cuti:
                inst.author.levels -= 2
                inst.author.save(update_fields = ['levels'])
            if inst.ys_t:
                inst.author.levels -= 2
                inst.author.save(update_fields = ['levels'])
            return inst
    

    本意是用户发布信息后,编辑信息时如果给标题“加粗”,变“颜色”时就会扣除用户积分 2. 如果不做此操作的话就不扣除积分

    问题是如果用户本身就已经“加粗”或变颜色了。那再编辑信息只改其它如标题或内容时,这样的情况就不再扣积分了。

    如上面代码只要编辑信息就会扣除相应的积分。 我现在想到的办法 一. 把加粗或变色单独写一个操作函数。 二. 在 models 或 forms 里 在修改信息时 直接在 def save()里实现。就是先取到修改前信息的 is_cuti ys_t 字段的值跟修改后的值做比较后再决定是否执行扣积分问题

    现在不知道怎么先取到修改前的值? 如上面所示代码都是取到的修改后的值。 在构造函数里 init 里取不到东西。也可能我写的代码不对

    不知道哪位朋友有什么方法能实现这个功能吗? 多谢了

    5 条回复    2024-06-21 10:19:12 +08:00
    djangovcps
        1
    djangovcps  
       8 天前
    self.instance = kwargs.pop('instance', None)
    这个应该能获取更新前的 model
    cleaned_data = self.cleaned_data
    这个能获取前段传的值
    daorougunzzz
        2
    daorougunzzz  
       8 天前
    有个 clean 函数用于数据校验,试下看看
    python30
        4
    python30  
    OP
       6 天前
    感谢各位,已经取到值了。
    python30
        5
    python30  
    OP
       6 天前
    @djangovcps self.instance = kwargs.get('instance', None)
    用 pop 也可以取得值,但是会把原先的数据删除
    取到值后,别的就是一个 if 比较语句就比较简单了。多谢了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3155 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 10:58 · PVG 18:58 · LAX 03:58 · JFK 06:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.