Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 787
Marco Aurélio Avatar asked Apr 11 '26 19:04

Marco Aurélio


1 Answers

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.

like image 60
pythad Avatar answered Apr 14 '26 09:04

pythad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!