Marco Aurélio
Marco Aurélio

Reputation: 23

Django is rendering without context. Why?

I am building a new framework for an institution. I'm currently working with Django to create the framework. When i was creating the "New user" form, i noticed that some parts of the page was rendering without context. Why is that?

Look:

view.py

from django.contrib.auth.models import User

def index(request):
    context = {
               'user': request.user,
               'userDB': User.objects.all()
              }
    return render(request, 'user/home.html', context)

def new_user(request):
    return render(request, 'users/new.html', {})

user/home.html

{% user.username %}

user/new.html

{% user.username %}

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index),                                        # User homepage
    url(r'^new/', views.new_user),                                  # Add user
    url(r'^(?P<user>[0-9]+)/edit', views.edit_user),            # Edit user
]

As you can see, there is no context available to render new_user, but it renders it. I am afraid this could bring some problems in the future. Although, it's the desired effect, but i don't understand it...

Upvotes: 3

Views: 879

Answers (1)

pythad
pythad

Reputation: 4267

You need to know that user instance of django.contrib.auth.models.User is always passed to the context for you by Django. It's just the same as request.user. Even if User isn't registered or logged in an instance of AnonymousUser will be passed.

Upvotes: 1

Related Questions