Django | Codecademy | Views

celeste·2022년 4월 11일
0

Codecademy Django

목록 보기
3/5

What are Views?

Views act as a link between Model data & Templates

  • a view is a function that takes HTTP request and returns a HTTP response
  • view describes which data you see, not how you see it

Steps of accessing a view via URL:

  1. A user visits a URL which sends a request for a resource to Django (e.g. navigating to a specific endpoint).
  2. Django looks into the framework for that URL path.
  3. If it finds a match and the path is linked to a particular view, its view function is called.
  4. The logic in that view function will be executed, usually communicating with the model and retrieving the requested data.
  5. The view then renders a template along with all the data to display it to the user.

As we create functions in views.py file, make sure to import functions in the urls.py file

ListView

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.

  • must import them from 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"
  • this means specifying the model we’re using Django will automatically try to find a template in <the_app_name>/<chosen_model_name>.html

CRUD w. Generic Views

Generic Views

# 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:

  • Notice that we first have also import CreateView from another module, django.views.generic.edit.
  • In the new class’s name, we append Create to the model name to get StudentCreate.
  • The argument is also different and is now CreateView.
  • The model remains the same, we still need to set the model we want this view to reference.
  • The template (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!
  • Speaking of input, to know what should go in the form, we have to provide a fields property. This is an array that contains a list of the model’s fields as strings.
    • In this case, we’re supplying our form template will include the options to fill in information about a student’s “first_name”, “last_name”, and “grade”.
  • With DeleteView, there’s no need to add in fields since if we’re deleting an instance, we’ll delete everything associated with that instance.

Adding Views to urls.py

  • URLconf가 views까지 도달할 수 있게 설정해주기.
  • 지금 문제는, Django's URL resolver는 request를 callable function에다 주길 원하지, class에 주기 원하지 않는다. 지금 우리 views.py는 class based이다!!
    • as.view()를 사용하면 class를 function 형으로 만들어준다
  • name attribute도 추가해줬다
    • name을 추가해줘서 빠르게 긴 URL대신 접근할 수 있다
    • URL을 바꾸더라도 name은 똑같으니 Django가 인식하기 편하다
# urls.py
 
urlpatterns = [
  path("students/", views.StudentList.as_view(), name="studentlist")
]

Using Primary Keys in URLs

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.

0개의 댓글