Last Updated: February 25, 2016
·
1.422K
· zorig

Django session usage

So as long as this is my first post, i thought, i should start with something very familiar with me. I have been using django for a while. About week ago i have to use django session, and i looked up here, but sadly no results. So i decided to write some tips that i'm using. First thing is first, this tip requires some knowledge to work on django. Hence i think there is no need to write template part.

So let's assume that we have a models.py like this:

class Book(models.Model):
    flight_from_where = models.CharField(max_length=30)
    flight_to_where = models.CharField(max_length=30)
    flight_departure = models.DateField()
    flight_return = models.DateField()

Obviously forms.py would be this:

class BookForm(forms.ModelForm):
    class Meta:
        model = Book

and views.py for this form above:

def Book(request):
    if request.method == 'POST':
        form = BookForm(request.POST)
        if form.is_valid():
            booking = form.save()
            request.session['pk']=booking.pk
            return HttpResponseRedirect('/details')
    else:
        form = BookForm()
    return render(request, 'book.html', { 'form' : form })

and second view to show what user's input are, which means often web app have to show what user's inputs are in order to better UX.

def details(request):
    book_form_id = request.session.get('pk')
    booking = Book.objects.get(id=book_form_id)
    return render(request, 'details.html', { 'booking' : booking }

At last urls.py

url(r'^book', 'app.views.Book'),
url(r'^details', 'app.views.details'),

I think this is it, So let me know if you guys(geeks) have any simple solution please let me know.