Add ModelForm Fields as Attribute to Object

后端 未结 1 1036
一整个雨季
一整个雨季 2021-01-26 06:42

I have a ModelForm for my Risk set up as:

class RiskForm(forms.ModelForm):
    class Meta:
        model = Risk
        fields = \'__all__\'
    def __init__(sel         


        
相关标签:
1条回答
  • 2021-01-26 06:59

    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.

    0 讨论(0)
提交回复
热议问题