Search code examples
pythondjangosessionmodels

Changing data in form.clean_data


I've been struggling for a few day with this.

I'm using django Python and all my objects have an abstract object that the user can't change and can't see in the pages, but he choses when he logs in. So when he logs in, he enters user, password and select this object and I want to make sure that everything inside the pages have that object related, so when he logs in with another instance doesn't see the previous ones.

Here it is my model: (as you can predict, all my objects have commonObject)

class Model(models.Model):
    name = models.CharField(max_length=200)
    thing = models.IntegerField()
    commonObject = models.ForeignKey(commonObject, editable=False)

Now my problem is that I can not save the commonObject. Please keep in mind that I'm using django-smarter, here it is the add_view code

action = self.action
form_kwargs = self.get_form_kwargs(action, request, *args, **kwargs)
if request.method == 'POST':
    form = self.get_form(action=action,
                        data=request.POST,
                        files=request.FILES,
                        **form_kwargs)
    if form.is_valid():
        form.cleaned_data['commonObject'] = pk.loads(request.session.get('commonObject'))
        print form.cleaned_data #Here the commonObject is the one that I want, but save doesn't seem to care
        instance = self.save_form(form)
        return self.add_success(request, instance)
else:
    form = self.get_form(action=action, **form_kwargs)
context = {'form': form}
return self.render_to_response(context)

My approaches were:

1) Save the commonObject in the save() method of the model rewriting it. The problem with this is that I can not access the request object (neither to save the common object in session or in another column of the User Object).

2) Changing form.clean_data doesn't seem to be working. Within this approach, I tried to serialize the object, which I succesfully did with "pickable" but Models.py is taking as the real one the previous form rather than the one I changed.

3) Using pre_save and post_save, but I don't have access to the request object in Models.py.

Could you please help me with this?


Solution

  • I think you cannot directly change data in form like you do. You must be save a form to create a data instance but not commit it yet then change the data you want. After you change everything you want then save it (with commit).

    e.g. (not test)

    if form.is_valid():
        instance = form.save(commit=False)
        instance.commonObject = pk.loads(request.session.get('commonObject'))
        instance.save()
        return self.add_success(request, instance)