Home > Net >  Saving values to django model through a for loop
Saving values to django model through a for loop

Time:11-20

I want to use a dictionary to store values in a model through a modelform and a view. Today I solve it like this:

form.variable_1 = dictionary['variable_1']
form.variable_2 = dictionary['variable_2']
form.variable_3 = dictionary['variable_3']
form.variable_4 = dictionary['variable_4']
form.variable_5 = dictionary['variable_5']
form.variable_6 = dictionary['variable_6']

The keys in the dictionary are identical to the field names for the values I want to store. I would like to make the function a bit more pythonic - something like this:

for field in form: 
    form.field = dictionary['field']

However, I'm not sure how to use the Django ORM to achieve this. The fields I want to iterate are numbered 3-28 in the list of fields, so I guess I would have to slice the fields somehow and create a list based on that?

edit:

models.py

class MyModel(Model):
user = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE)
Instance_name = CharField(max_length=200, default='')
Instance_text = TextField(default='')
variable_1 = IntegerField(null=True)

There's a total of 30 variables like variable 1 following it.

forms.py:

class MyModelMF(ModelForm):
class Meta:
    model = MyModel
    fields = [
        'Instance_name',
        'Instance_text'
    ]

    widgets = {
        'Instance_text': Textarea(attrs={"style": "height:4em;" "width:25em;"})
    }

views.py (up until iteration starts, excluded return render etc for simplicity)

def create_instance(request):
form = MyModelMF()
if request.method == 'POST':
    form = MyModelMF(request.POST)
    if form.is_valid()
        form = form.save(commit=False)
        form.user = request.user
        form.variable_1 = scores_dict['variable_1']

CodePudding user response:

You can use the built-in function setattr to set an attribute of your instance by name. Iterate over the keys and values in your dict and use the keys as the attribute names when calling setattr

if form.is_valid()
    form = form.save(commit=False)
    form.user = request.user
    for field_name, value in scores_dict.items():
        setattr(form, field_name, value)
    form.save()
  • Related