0

I have a problem with Django form instantiation. To sum up, here's my code. In a view, I have to generate a context which is related to many objects.

def my_view(request):
    myObjects = ObjectFromModels.objects.filter(some_attribute = '1234')
    for item in myObjects:
        form_related = AssociatedForm(item_pk = item.pk)
        my_context[item] = form_related

class AssociatedForm(forms.Form):
    # attributes

    def __init__(self,item_pk,*args,**kwargs)
        super(AssociatedForm,*args,**kwargs)
        if item_pk : 
            obj = ObjectFromModels.objects.get(pk=item_pk)
            self.someAttribute = obj.calling_function() # It returns a list

Here's the trouble, in the view, after the iteration, for all items, the value of my_context[item.name] is overriden by the value of the last element of the iteration

In order to debug, I printed the results :

def my_view(request):
        myObjects = ObjectFromModels.objects.filter(some_attribute = '1234')
        for item in myObjects:
            form_related = AssociatedForm(item_pk = item.pk)

            print(form_related.someAttribute)
            my_context[item.name] = form_related

        for key,val in my_context:

            print(key)
            print(val.someAttribute)

Let's take an example. The filter function returns 3 objects : [ObjectA,ObjectB,ObjectC]

and calling the calling_function() from these objects returns :

  • for item A : ['aze','zer','ert']
  • for item B : ['qsd','sdf','dfg']
  • for item C : ['wxc','xcv','vbn']

Logically, after all iterations, I would have this in my context. The thing is that, it returns :

{<ObjectA>:['wxc','xcv','vbn'],
 <ObjectB>:['wxc','xcv','vbn'],
 <ObjectC>:['wxc','xcv','vbn']}

I first though that it was a problem of reference but both forms in my context have a different memory addresses. I also tried deep_copy but nothing changed.

I suspect that what I consider as 3 different forms to be one form but I can't explain why because as I said, both have different memory addresses. And why, in the loop, the display of my form attributes is right but outside the loop, something is messing up and parsing the last dict to both of the entries of my context dict ?

Does someone have a clue to identify the problem ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Kobz
  • 469
  • 6
  • 17
  • Have you had a look at modelforms and model formsets already? If so, why couldn't they help you? If not, please have a look at https://docs.djangoproject.com/en/dev/topics/forms/modelforms/ – Dr.Elch Apr 14 '14 at 11:37
  • Yes I already checked modelforms but the thing is that it's not linked to a specific model. It's more like a form which is creating various instances of objects from the data provided to the form which are related by foreign key / many-to-many fields. – Kobz Apr 14 '14 at 12:09

0 Answers0