Reputation: 173
I am trying to learn Django by watching the Django course by Cory Schafer, and I'm just confused about the part where Cory used redirect after the registration process.
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}!')
return redirect('blog-home')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
He used the return redirect('blog-home')
and managed to show the message Account created for {username}
in the template. But I'm not sure how he managed to access that message in the template without ever passing it similar with what we do with render method.
Example of render method I learned is below, it's always passing the 3rd argument so that in the template we can manage to access it. But I have no idea how the message was passed via redirect method.
return render(request, 'blog/home.html', context)
Upvotes: 1
Views: 69
Reputation: 615
Django has some build-in context processors which are applied on top of context data and are universally available in every template. django.contrib.messages.context_processors.messages
is one such.
Thus the messages are universally accessible to every template. You can read more here https://docs.djangoproject.com/en/3.2/ref/templates/api/#django.template.Context . Furthermore you can find the list of all the context processors in your settings.py file inside the Templates options -
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Here you can see the messages context processor.
Upvotes: 1