Add ModelForm Fields as Attribute to Object

不羁的心 提交于 2019-12-02 16:46:41

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/40238993/add-modelform-fields-as-attribute-to-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!