Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you use the GET parameters like you suggsted (<code>?ui=2</code>), then you shouldn't have to touch urls.py at all. Your decorator can inspect <code>request.GET['ui']</code> and find what it needs.</p> <p>To avoid hardcoding template names, maybe you could wrap the return value from the view function? Instead of returning the output of render_to_response, you could return a tuple of <code>(template_name, context)</code> and let the decorator mangle the template name. How about something like this? <strong>WARNING: I haven't tested this code</strong></p> <pre><code>def ab_test(view): def wrapped_view(request, *args, **kwargs): template_name, context = view(request, *args, **kwargs) if 'ui' in request.GET: template_name = '%s_%s' % (template_name, request.GET['ui']) # ie, 'folder/template.html' becomes 'folder/template.html_2' return render_to_response(template_name, context) return wrapped_view </code></pre> <p>This is a really basic example, but I hope it gets the idea across. You could modify several other things about the response, such as adding information to the template context. You could use those context variables to integrate with your site analytics, like Google Analytics, for example.</p> <p>As a bonus, you could refactor this decorator in the future if you decide to stop using GET parameters and move to something based on cookies, etc.</p> <p><strong>Update</strong> If you already have a lot of views written, and you don't want to modify them all, you could write your own version of <code>render_to_response</code>.</p> <pre><code>def render_to_response(template_list, dictionary, context_instance, mimetype): return (template_list, dictionary, context_instance, mimetype) def ab_test(view): from django.shortcuts import render_to_response as old_render_to_response def wrapped_view(request, *args, **kwargs): template_name, context, context_instance, mimetype = view(request, *args, **kwargs) if 'ui' in request.GET: template_name = '%s_%s' % (template_name, request.GET['ui']) # ie, 'folder/template.html' becomes 'folder/template.html_2' return old_render_to_response(template_name, context, context_instance=context_instance, mimetype=mimetype) return wrapped_view @ab_test def my_legacy_view(request, param): return render_to_response('mytemplate.html', {'param': param}) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload