bkev
bkev

Reputation: 1905

How to wrap Django FormPreview in a view

I have a situation (shopping cart checkout sequence) where the workflow used in Django's FormPreview contrib app looks perfect, except I need to have some view logic occur before I call it (I can't call the checkout sequence if the cart is empty, for example). From the docs, it looks like you call FormPreview directly from the urlconf like so:

(r'^post/$', SomeModelFormPreview(SomeModelForm))

...and it calls the overridden done() method for the FormPreview directly (without a view).

Since my urls.py is similar to:

url(r'^checkout/$', 'checkout', {'SSL': settings.ENABLE_SSL }, name = 'checkout'),

and my view is similar to:

def checkout(request):
    if cart.empty(request):
        cart = urlresolvers.reverse('shopping_cart')
        return HttpResponseRedirect(cart)
    if request.method == 'POST':
        checkoutform = CheckoutFormPreview(CheckoutForm)

This last line is where I'd like to call it, but can't figure out how to wrap it... Suggestions?

Upvotes: 3

Views: 277

Answers (1)

Alasdair
Alasdair

Reputation: 309009

It looks like CheckoutFormPreview(CheckoutForm) returns a callable view that you can add to your url config. If you call it in your view, you just need to pass the required request argument. Then return the result.

Putting it together, you have (untested):

if request.method == 'POST':
    form_preview_view = CheckoutFormPreview(CheckoutForm)
    return form_preview_view(request)

Upvotes: 2

Related Questions