Views act as a link between Model data & Templates
Steps of accessing a view via URL:
As we create functions in views.py
file, make sure to import functions in the urls.py
file
Django provides us with base views that are inherited from the class view
(여러가지 base view를 상속)
Ex, Listview
상속을 받으면, it takes care of the logic in order to display multiple instances of a table in the database.
django.views.generic
at the top of our file, along with our Student
model# views.py
from .models import Student
from django.views.generic import ListView
Once imported we can specify what model we’ll be using the ListView
for:
# views.py
class StudentList(ListView):
model = Student
template_name = "schoolapp/student.html"
model
we’re using Django will automatically try to find a template in <the_app_name>/<chosen_model_name>.html
# views.py
from .models import Student
from django.views.generic import ListView
from django.views.generic.edit import CreateView
class StudentCreate(CreateView):
model = Student
template_name = "schoolapp/student_create_form.html"
fields = ["first_name", "last_name", "grade"]
key differences between ListView vs. CreateView, UpdateView, DeleteView:
CreateView
from another module, django.views.generic.edit
.StudentCreate
.CreateView
.model
remains the same, we still need to set the model we want this view to reference.template_name
) is also different. That is because to create a Student
instance, we’ll need to get some user input which means we should create a form template!fields
property. This is an array that contains a list of the model’s fields as strings.DeleteView
, there’s no need to add in fields since if we’re deleting an instance, we’ll delete everything associated with that instance.as.view()
를 사용하면 class를 function 형으로 만들어준다name
attribute도 추가해줬다# urls.py
urlpatterns = [
path("students/", views.StudentList.as_view(), name="studentlist")
]
URL path에 <p>
추가함으로써 specific instance page로 갈 수 있다. ex. student/10
# urls.py
urlpatterns = [
# ... Other paths
path("students/", views.StudentList.as_view(), name="studentlist"),
path("students/<pk>", views.StudentUpdate.as_view(), name="studentupdate")
]
ex) If we navigate to students/4
, Django would grab the value, 4
, as the primary key and access the database in order to retrieve that record.