2.3 KiB
2.3 KiB
status: #doc Tags: #python/django links: Date: 2024-06-22
views
making simple functional view
- in my_app folder inside views.py add
# index() ==> Hello World
def index(request):
return HttpResponse("Hello World")
- and import
HttpResponse
formdjango.shortcuts
with adding it to first line like below
from django.shortcuts import render,HttpResponse
[!INFO] what it do? we get client request and then we response with text hello_world, note that we use
HttpResponse
so we can use text to answer client and request is what we get from client
urls
add simple url
- first import your view like this
from my_app.views import index
- go to config or your project folder inside of url.py file route to home like this
# my_site.com/ ==> index()
urlpatterns = [
path('',index),
]
[!INFO] urls are used to route requests to views for checking witch view we call we use urlpatterns list
[!info] its better to add / to end of path , example: about or about/ both fire same view
dynamic routing
when we want to load pages base on variables we send variables from urls ==> views/functions and it will produce our page base on variables
- Example : we send name of person in url and it say hello to them
for this first we want to get person name from url
send variable from urls
- first we send variable to view we want (we can first make url or view it doesn't matter)
from my_app.views import hello
# path ('adreess_you_want/<type_of_variable:variable>/',name_of_view)
# my_site.com/hellome/first_name ==> hello(first_name)
urlpatterns = [
path('hellome/<str:first_name>',hello),
]
receive variable in views
inside views.py we add this
def hello(request,first_name):
return HttpResponse(f"Hello {first_name}")
using templates
inside views.py we use render function like this
- app level template
def hello(request):
return render(request,"my_project/home.html")
- inline variables
def hello(request):
return render(request,"my_project/home.html",{'my_var':'bar' })
- context
def hello(request):
context:{
movies:["avatar,matrix,spider-man"]
}
return render(request,"my_project/home.html",context)
- url variables ???