将ModelForm字段添加为对象的属性 [英] Add ModelForm Fields as Attribute to Object

查看:154
本文介绍了将ModelForm字段添加为对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ModelForm为我的风险设置为:

  class RiskForm(forms.ModelForm):
Meta:
model = Risk
fields ='__all__'
def __init __(self,* args,** kwargs):
progid = kwargs.pop('progid')
super(RiskForm,self).__ init __(* args,** kwargs)
dict_of_fields = {}
all_char = Program.objects.get(id = progid).char_set.all()
在all_char中的char:
c = []
在char.cat_set.all()中的cat:
c.append((cat.label,cat.label))
dict_of_fields [char.label] = c
self.fields [char.label] = forms.ChoiceField(c)

风险对象定义为:

  class Risk(models.Model):
program = models.ForeignKey(Program,on_delete = models.CASCADE)
label = models.CharField(max_length = 200,default ='')

def __str __(self):
return self.label

但是,我想存储额外的我在我的Risk对象下创建的数据库中的字段。
我现在拥有它只存储两个属性程序和标签。但是,我还想将特征的答案存储到我的数据库中以备以后使用。



有关如何设置内容的更多信息:基于变量属性的Jango表单



我的ModelForm的打印屏幕: https://gyazo.com/89c9833613dbcc7e8d27cc23a3abaf72



是否可以将我的Risk Object下的所有6个答案存储在我的数据库中?如果是这样,我该怎么做?

解决方案

Django中的表单是一个用户界面对象 :它给用户一组字段来输入答案,检查他们提供的数据是否有效,并将其从文本转换为所需的Python数据类型(int,date等)。它不必与任何特定的模型相关,而且通常不会。例如,在线商店可能会有购买选择表单,将可能的订单数据添加到用户的会话中,而不是立即对产品或库存对象执行任何更新。之后,在结帐时发生。



ModelForm假定有一个Model to Form关系。当用户的答案和单个模型实例之间存在简单的关系时,通常是正确的方法。



如果您有一种情况,用户的答案直接创建与任何特定对象的不太直接关系的多个数据库对象,您可能不想要一个ModelForm,只是一个表格。也可能不是基于模型的视图,而是基于功能的视图。然后,您可以在从URL解析器获取参数的视图之间进行所需的任何操作,然后将表单显示给用户。同样,在确定用户的POST数据有效并且告诉用户他的提交的请求是否成功(或不是,为什么)之间的任何事情之间。



在这种情况下,我不清楚你想要存储所有六个答案。如果有一个预定的相当小的答案,你可以有一个单一的对象与六个?十?可以为空的可能的一组字段,表示该对象没有该实体。或者可能更好的是,您可以创建一组回答对象,每个对象与Risk对象具有Foreign Key关系,后来参考Risk.answer_set(所有与您的风险对象具有外键关系的Answer对象)。这是开放式的,一个Risk对象可以有从零到bignum相关的答案。


I have a ModelForm for my Risk set up as:

class RiskForm(forms.ModelForm):
    class Meta:
        model = Risk
        fields = '__all__'
    def __init__(self, *args, **kwargs):
        progid = kwargs.pop('progid')
        super(RiskForm, self).__init__(*args,**kwargs)
        dict_of_fields = {}
        all_char = Program.objects.get(id=progid).char_set.all()
        for char in all_char:
            c = []
            for cat in char.cat_set.all():
                c.append( (cat.label, cat.label) )
            dict_of_fields[char.label] = c
            self.fields[char.label] = forms.ChoiceField(c)

Where the Risk Object is defined as:

class Risk(models.Model):
    program = models.ForeignKey(Program, on_delete=models.CASCADE)
    label = models.CharField(max_length=200, default='')

    def __str__(self):
        return self.label

However, I want to store the extra fields that I have created into my database under my Risk object. As I have it now, it only stores the two attributes 'program' and 'label'. However, I also want to store the answers to the characteristics into my database for later usage.

For more information about how I've set things up: Django Form Based on Variable Attributes

And a print screen of my ModelForm: https://gyazo.com/89c9833613dbcc7e8d27cc23a3abaf72

Is it possible to store all 6 answers under my Risk Object in my database? If so, how do I do that?

解决方案

A form in Django is a user interface object: it gives the user a set of fields to type answers into, checks that the data which they have supplied is valid, and converts it from text to the desired Python data-type (int, date, etc.). It does not have to relate to any particular model, and often doesn't. For example, an online shop is likely to have purchase selection forms which add data concerning possible orders into the user's session, rather than immediately performing any sort of update on a Product or Stock object. That happens later, at checkout.

A ModelForm assumes there is a Model to Form relationship. It is typically the right way to go when there is a simple relationship between the user's answers and a single model instance.

If you have a situation where the user's answers direct the creation of multiple database objects with a less direct relationship to any particular object, you probably don't want a ModelForm, just a Form. Also probably not a model-based view, but a function-based view. You can then do anything you need to between the view picking up the parameters from the URL parser, and displaying the form to the user. Likewise, anything between the view determining that the user's POST data is valid and telling the user whether his submitted request succeeded (or not, and why).

In this case I'm not clear how you want to store all six answers. If there's a predetermined fairly small set of answers you could have a single object with six? ten? possible sets of fields which are nullable to indicate that this object doesn't have that entity. Or, probably better, you could create a set of Answer objects each of which has a Foreign Key relationship to the Risk object, and later refer to Risk.answer_set (all the Answer objects which have a foreign key relationship to your risk object). This is open-ended, a Risk object can have anything from zero to bignum associated Answers.

这篇关于将ModelForm字段添加为对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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