GXM100
GXM100

Reputation: 467

Passing Form Data to View

I have the following view:

views.py

def PackingListView(request):
    if request.method == "POST":
        form = PackingListForm(request.POST)
        if form.is_valid():
            if 'preview' in request.POST:
                request.session['data'] = form.cleaned_data
                return redirect('myview')
  ....

I would like to take the data in form and pass it to this next view, and set the data variable equal to it. This was previously working, but once I added a foreign key into this form, the session no longer works as it is not serializable. What approach is the safest for me to take here?

views.py

class myview(View):
    def get(self, request, *args, **kwargs):

        data = request.session.pop('data', {})#this won't work  now

        pdf = render_to_pdf('packlist_preview.html', data)
        return HttpResponse(pdf, content_type='application/pdf')

Also in case it is needed - here is the URL for myview

url(r'^myview/', views.myview.as_view(), name='myview'),

Upvotes: 0

Views: 56

Answers (1)

Alasdair
Alasdair

Reputation: 309109

You should be able to serialize the data if you replace the model instance with its id.

data = form.cleaned_data
# remove object from data dict
related_object = data.pop('related_object')
# add in a reference
data['related_object_id'] = related_object.pk
# now you should be able to serialize object
request.session['data'] = data

Then in the next view, you can fetch the object from the database using its id

data = request.session.pop('data', {})
related_object_id = data.pop('related_object_id', None)
if related_object_id:
    try:
        data['related_object'] = RelatedObject.objects.get(pk=related_object_id)
    except RelatedObject.DoesNotExist:
        pass

Upvotes: 1

Related Questions