Basic Django, Let's recap!

 Go into urls.py

we have multiple urls files here, we're going to use two urls files here. one for Root urls and the other for our specific app. 

from django.contrib import admin
from django.urls import path, include


To create a view we're going to use function. 

def home(request):
    return HttpResponse('Home page')

(Request object is going to be the Http object, telling us what kind of request method is sent, what kind of data is being passed in what's the user sending to the backend here. )

Home page, it's going to be a string that we're going to render out 


Add this one too 

from django.http import HttpResponse


Now we're going into urls and we're going to say when somebody goes to the Homepage, 
we're setting a path so that's imported. 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home),
]
'' : home page is going to be the root domain,
home : we're going to send the user to home so we're going to trigger this function 
tell which function we're going to trigger and we're going to return back the http response 






Now you see "Home page" 







Let's make one more page. .
def room(request):
    return HttpResponse('Room')

and add some parameters..
 path('room/', room)



 Now you see room

at our domain/room 





OK.  Let's move on to the next step. 


let's take these two views into main/views.py 
def home(request):
    return HttpResponse('Home page')

def room(request):
    return HttpResponse('Room')

and delete this from django.http import HttpResponse

Create urls.py file inside main folder (it can be base or whatever you named the folder)
from django.urls import path

from . import views

urlpatterns = [
path('', views.home, name="home"),
path('room/', views.room, name="room")
]

from . -> means views.py is the same folder

path has 3parameters like this '', views.home, name="home"

and make "from dango.http import HttpResponse into views.py 

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def home(request):
    return HttpResponse('Home page')

def room(request):
    return HttpResponse('Room')
 

To make it work, we need to add "include" into core urls.py, which is in mysite folder
from django.contrib import admin
from django.urls import path, include
from django.http import HttpResponse


urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('main.urls'))
 
include('main.urls') means the user is going to go to this page it's going to match the route, so to main/urls.py 



Popular posts from this blog

[Python] Dictionary

[Visual Design 2/3]

[JavaScript] For loop , Function