0

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?

Community
  • 1
  • 1
T. Pijl
  • 23
  • 5
  • You can create Answer model and have many to many relationship with your Risk model. – Kishan Mehta Oct 25 '16 at 12:23
  • Could you please elaborate? I'm still learning Python and my supervisor said that I should probably avoid many to many relationships. If there is no other way, I see no other way than to use them. However, I have no idea how to construct this. Could you help me / give me some general (outline) code on how to write this? – T. Pijl Oct 25 '16 at 12:38
  • I would suggest you to ask your supervisor why many-to-many relationship should be avoided!! However, general idea I follow to decide weather this relationship is going to be ForeighKey, OneToOneField or ManyToManyField: If you can say 'one risk can have many answers, one answers can be in many risks' Then use ManyToManyField. If you can say 'one risk can have many answers, one answers can be in One risks' Then use Foreignkey. I want to know how your answers are related with risk or programs? – Kishan Mehta Oct 25 '16 at 12:49
  • Each Risk has multiple characteristics (and thus answers) and each answer can be at multiple risks (For example: Risk 1: {Occupancy: Farm, Construction: Wood Frame} Risk 2: {Occupancy: Farm, Construction: Metal Frame}). I can see how many-to-many fields come in handy. However, how do I initialize this without shell commands (I can do mostly everything in the Shell, however, programming in models / forms is still quite tough for me) – T. Pijl Oct 25 '16 at 12:59
  • I am not sure if you read this : https://docs.djangoproject.com/en/1.10/topics/db/examples/many_to_many/ It shows with examples how to create many to many objects and save them. – Kishan Mehta Oct 25 '16 at 13:33
  • Yes, I've read most of the documentation about everything (I've gone through the whole first Google page of every subject). However, I see this as shell commands and not how to write this into a script / Django file dynamically. That's what I'm mostly struggling with, going from shell commands (which works most of the time) to Django scripts (model - form - view - url). – T. Pijl Oct 25 '16 at 21:01
  • You can write your functionalities in your view and wire them up with url in your urls.py. – Kishan Mehta Oct 26 '16 at 05:41

1 Answers1

0

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.

nigel222
  • 7,582
  • 1
  • 14
  • 22
  • Based on your first three paragraphs, I'll probably need to use a form and a function based view. Thank you for that, will look into that later this day. Considering your fourth paragraph. There is no predetermined anything in my project, that's also the 'problem'. One can arbitrarily create a program with an "unlimited" amount of characters and each character has an "unlimited" amount of possible categories to choose from. Thus I have to use parent id's to get the right ones, I cannot make predetermined sets of answers. – T. Pijl Oct 25 '16 at 13:14
  • Based on that you need Program, Character and Category models. Each category has a foreign key to a Character (so a Character has a set of categories) and each Character has a foreign key to a Program. A user chooses a Program. You can then dynamically construct a form with questions based on Program's Character_set answers to which have choices based on each Character's category_set (if I understand you...) The answers which come back maybe get stored in a bunch of Answer objects which maybe have foreign keys to the Person who submitted them and to the Character to which they relate. – nigel222 Oct 25 '16 at 14:06
  • Sorry for the late answer, was away for a while. Yes, I have that. Up until the dynamically constructed form. What I'm trying to get answered with this question is how I store those answers into an Answer object. Furthermore, all the answers of one form need to have the same parent and no other (thus not the Person who submits, but the Risk that corresponds with these answers). Will dig deeper into the way of Answer objects rather than Risk objects (Or maybe Answer with ForeignKey Risk). Thanks a lot anyway! – T. Pijl Oct 25 '16 at 20:59