An Interest In:
Web News this Week
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
- April 17, 2024
September 5, 2022 11:39 am GMT
Original Link: https://dev.to/jesuissuyaa_/django-cheatsheet-views-135f
Django cheatsheet - Views
View are something that accepts a request, and returns some kind of a response.
In the render()
function, you can pass a context
that are variables you can pass to your template.
how to add a new view
- define the URL in
your-project/your-app/urls.py
- add a view in
your-projects/your-app/views/new-view.py
- import the view in
your-projects/your-app/views/__init__.py
shortcuts: render, redirect
from django.shortcuts import render, redirectdef index(request): students = Students.objects.all() context = { "students": students } return render("index.html", context)
messages
https://docs.djangoproject.com/en/4.1/ref/contrib/messages/#using-messages-in-views-and-templates
If you want to use "messages" (e.g. flash messages, toast messages in other frameworks), you can use the messages framework.
Add this import,
from django.contrib import messages
... and call the messages like this in your views.
messages.debug(request, '%s SQL statements were executed.' % count)messages.info(request, 'Three credits remain in your account.')messages.success(request, 'Profile details updated.')messages.warning(request, 'Your account expires in three days.')messages.error(request, 'Document deleted.')
The template can show the messages like this:
{% if messages %}<ul class="messages"> {% for message in messages %} <li>{{ message }}</li> {% endfor %}</ul>{% endif %}
It' s important to iterate all the messages, otherwise the messages will not be cleared.
from django.contrib import messages# view to create new studentdef new(request): if request.method == "POST": # do something with the form student.save() # send messages messages.success(request, "saved student")
Original Link: https://dev.to/jesuissuyaa_/django-cheatsheet-views-135f
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To