繁体   English   中英

Django 获取 forms 的 __init__ 中某个字段的值

[英]Django get the value of a field in the __init__ of forms

在进行更新之前,我需要有一个字段的值。 forms.py

class Form_Rol(forms.ModelForm):
     class Model:
         model = My_Model
         fields = "__all__"

     def __init__(self, *args, **kwargs):
         '''I want to do this'''
         value_coming_from_update = self.fields['name']
         print(value_coming_from_update)

Output.... <django.forms.fields.CharField object 在 0x0000026649558DC0> 我如何打印实际值?

我不能在init中使用 self.cleaned_data.get('name') 。 它给了我一个错误(AttributeError: 'Form_Rol' object has no attribute 'cleaned_data')

在使用数据(也称为“绑定”)实例化表单并且cleaned_data is_valid()返回 True 之前,clean_data 不存在。 所以根本不可能在__init__时间访问它。

你能解释一下你想要完成什么吗?

大胆猜测,您可能希望在保存之前进一步检查 ModelForm 生成的 object。 你这样做的方式是

if form.is_valid():
    instance = form.save( commit=False)
    # further checking of instance...
    if instance.ok_to_save():
        instance.save()

暂无
暂无

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

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