[Fixed]-How to get models current values from a view to another?

1👍

Easy and fast way: Sessions

If all you need is a list of strings or a single string, you can just use sessions. You can read about them in detail in the docs. Just save the names in some key, display them and clear them.

Better, more future proof solution but slightly more complicated: Models

When you are selling something, it is desirable to keep around some record of what the user bought. This can be helpful when system fails (trust me, it will) or to keep a record of everything.

It can be something as simple as:

class Transaction(models.Model):
    gig = models.ForeignKey(Gig)
    user = models.ForeignKey(User)

Now you refactor your view in 2 ways:

  1. Only the user in the transaction should be able to see the content on it.
  2. Add the pk of the Gig to the url you redirected to.

Your source view should use a redirect like:

def checkout_payment(request):
    customer_id = request.user.profile.stripe_id
    if request.method == 'POST':
        try:
            gig = Gig.objects.get(id=request.POST.get('gig_id'))
        except Gig.DoesNotExist:
            return redirect(reverse('purchase_error_detail'))
    new_transaction = Transaction.objects.create(user=request.user, gig=gig)
    return redirect(reverse('purchase_confirmation_detail', kwargs={'pk': new_transaction.pk}))

And your destination view will be something like:

def checkout_confirmation(request, *args, **kwargs):
    new_transaction = Transaction.objects.get(kwargs.get('pk'))
    if request.user != new_transaction.user:
        return HttpResponseForbidden() # You can raise Http404 here too to hide the resource, like github does
    return render(request, 'purchase/confirmation.html', {'gig': transaction.gig})

Now you have access to everything you need to display.

Leave a comment