pomegranate
pomegranate

Reputation: 765

Django - view for activation on all sub-urls

On my site, a verification code is sent out by email once a user registers. Until the user verifies their account by typing in the code, a banner (positioned similar to the red banner about outdated django docs at the top here: https://docs.djangoproject.com/en/1.2/ref/forms/validation/) is displayed on all the sub-pages of the site that says "Enter Verification Code." with a form to enter the verification code.

This is my first time building a django site, and I am only familiar with how to tie a particular url to a single view. Since my view for account_activation needs to be present on all the subpages (while the user is logged in), what is the best way to go about doing this?

My urls.py is so far as follows:

#urls.py

....
url(r'^$', views.register_user),
url(r'^accounts/login/$', user.login),
url(r'^accounts/logout/$', user.logout),
url(r'^accounts/register/$', user.register_user),

Thanks for your help!

Upvotes: 1

Views: 108

Answers (1)

dhana
dhana

Reputation: 6525

You can use django middleware, check the user is logged or not. If user is logged you can find the activation flag. If activation flag is false then you can attach the some message variable your request META tag.

Middleware:

Middleware is a framework of hooks into Django’s request/response processing. It’s a light, low-level “plugin” system for globally altering Django’s input or output.

Here is your middleware,

from django.contrib.auth.models import User

class FlashActivationMiddleware():
     def process_request(request):
         if request.user.is_authenticated():
            if not request.user.is_active_email:
               request.META["message"] = "You Email is not activated"

In settings:

Add django.core.context_processors.request in your settings file in TEMPLATE_CONTEXT_PROCESSORS then you would be able to use the request in template without explicitly passing it in request context.

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.request', # this one
)

In base.html:

{% if request.META.message %}
   {{ request.META.message }}
{% endif %}

Note: is_active_email is a django user model field external attachment.

Hopes this helps you.

Upvotes: 1

Related Questions