Sometimes you want to show a user a different feature. Or you want to test it in the production environment without affecting the other users. Or you have a group of beta testers for which you rely on early feedback to improve your app. Below is how to do this using django-waffle .

Install django-waffle

Install the waffle package by running:

pip install django-waffle

Open your app's settings.py and:

add waffle to INSTALLED_APPS . add waffle.middleware.WaffleMiddleware to MIDDLEWARE_CLASSES .

And you're ready to go.

Create the beta testers group

Note: If you want to reuse an already existing group, just note its id for the next step.

Open a shell with:

./manage.py shell

and create a user group (adjust the first line if you use another group Model other than the one from django.contrib.auth ):

from django.contrib.auth.models import Group group = Group() group.name = 'Beta testers' group.save() group.id

Note the id of the new group for the next step.

Create a flag

Note: you can also do this on the admin site.

Reusing the previous shell:

from waffle.models import Flag flag = Flag() flag.name = 'new_feature' flag.group = 72 # replace 72 by the id from the previous step flag.save()

Use a flag in templates

Now that you have everything setup, it's time to use the flags in the code.

If you want to show a difference in a template, just add the waffle_tags and use the flag as you'd use an if :

{% flag flag_name %} Flag is active! {% else %} Flag is inactive! {% endflag %}

Use a flag in views

If you want to switch between different codes in views, just import waffle at the beggining of the file and then protect the differences with:

if waffle.flag_is_active(request, 'new_feature'): # Behavior if flag is active. else: # Behavior if flag is inactive.

Final notes

Don't overuse flags. Flags can be changed at runtime, so, for testing, you should test all the possible combinations. That adds a maintenance cost (in time and resources). As a rule of thumb I try to keep flags to a maximum of three at any point in time in a project.

Flags can also be used for phased roll-outs in Django. Check the documentation for that use case.

See the rest of the documentation at http://waffle.readthedocs.org/en/

Happy coding!