본문 바로가기

CBV (Class Based Views) 본문

개발/Django

CBV (Class Based Views)

Louisus 2020. 5. 13. 16:08
728x90

1. 'Hello World' with CBVs

 

# templates/index.html

 

{% extends "base.html" %}

{% block body_block %}

  <h1>Hello World! Index Page Home</h1>

{% endblock %}

 

# templates/base.html

 

<!DOCTYPE html>

<html lang="en" dir="ltr">

  <head>

    <meta charset="utf-8">

    <title>Base</title>

    <-- Bootstrap-->

 

  </head>

  <body>

    <div class="container">

      {% block body_block %}

      {% endblock %}

    </div>

   

  </body>

</html>

 

# urls.py

 

from django.contrib import admin

from django.urls import path

from basic_app import views

 

urlpatterns = [

    path('admin/', admin.site.urls),

    path('', views.CBView.as_view())

]

 

# views.py

 

from django.shortcuts import render

from django.http import HttpResponse

from django.views.generic import View

 

class CBView(View):

    def get(self, request):

        return HttpResponse("CLASS BASED VIEWS ARE COOL!")

 

 

2. Template Views with CBV

 

-        Function Based View

def index(request):

                    return render(request, ‘index.html’)

 

-        Class Based Template View

Class IndexView(TemplateView):

                    Template_name = ‘index.html’

 

# index.html

 

{% extends "base.html" %}

{% block body_block %}

  <h1>Testing TemplateView!</h1>

  <h2>Injected Content: {{ injectme }}</h2>

{% endblock %}

 

# urls.py

 

from django.contrib import admin

from django.urls import path

from basic_app import views

 

urlpatterns = [

    path('admin/', admin.site.urls),

    path('', views.IndexView.as_view())

]

 

# views.py

 

from django.shortcuts import render

from django.views.generic import View, TemplateView

 

class IndexView(TemplateView):

    template_name = 'index.html'

 

    def get_context_data(self, **kwargs):

        context = super().get_context_data(**kwargs)

        context['injectme'] = 'BASIC INJECTION!'

        return context

 

3. Detail View and List View

 

# models.py

 

from django.db import models

 

# Create your models here.

class School(models.Model):

    name = models.CharField(max_length=256)

    principal = models.CharField(max_length=256)

    location = models.CharField(max_length=256)

 

    def __str__(self):

        return self.name

 

class Student(models.Model):

    name = models.CharField(max_length=256)

    age = models.PositiveIntegerField()

    shcool = models.ForeignKey(School, related_name='students', on_delete=models.CASCADE)

 

    def __str__(self):

        return self.name

 

# admin.py

 

from django.contrib import admin

from basic_app.models import School, Student

 

# Register your models here.

admin.site.register(School)

admin.site.register(Student)

 

# basic_app/templates/basic_app/html files

 

# views.py

 

from django.shortcuts import render

from django.views.generic import View, TemplateView, ListView, DetailView

from . import models

 

class IndexView(TemplateView):

    template_name = 'index.html'

 

class SchoolListView(ListView):

    # my own context name

    context_object_name = 'schools'

    model = models.School

    # Automatically return school_list

 

 

class SchoolDetailView(DetailView):

    context_object_name = 'school_detail'

    # Automatically return school

    model = models.School

    template_name = 'basic_app/school_detail.html'

 

# base.html

 

<!DOCTYPE html>

<html lang="en" dir="ltr">

  <head>

    <meta charset="utf-8">

    <title>Base</title>

    <-- Bootstrap-->

  </head>

  <body>

    <nav class="navbar navbar-default navbar-static-top">

      <ul class="nav navbar-nav">

        <li><a class="navbar-brand" href="{% url 'basic_app:list' %}">Schools</a></li>

        <li><a class="navbar-link" href="{% url 'admin:index' %}">Admin</a></li>

        <li><a href="#"></a></li>

      </ul>

    </nav>

    <div class="container">

      {% block body_block %}

      {% endblock %}

    </div>

 

  </body>

</html>

 

# basic_app/templates/basic_app/basic_app_base.html

 

<!DOCTYPE html>

<html lang="en" dir="ltr">

  <head>

    <meta charset="utf-8">

    <title>Base</title>

    <-- Bootstrap-->

  </head>

  <body>

    <nav class="navbar navbar-default navbar-static-top">

      <ul class="nav navbar-nav">

        <li><a class="navbar-brand" href="{% url 'basic_app:list' %}">Schools</a></li>

        <li><a class="navbar-link" href="{% url 'admin:index' %}">Admin</a></li>

        <li><a href="#"></a></li>

      </ul>

    </nav>

    <div class="container">

      {% block body_block %}

      {% endblock %}

    </div>

 

  </body>

</html>

 

# basic_app/templates/basic_app/school_detail.html

 

{% extends 'basic_app/basic_app_base.html' %}

{% block body_block %}

  <div class="jumbotron">

    <h1>Welcome to the School Detail Page</h1>

    <h2>School details:</h2>

    <p>Name: {{school_detail.name}}</p>

    <p>Principal: {{school_detail.principal}}</p>

    <p>Location: {{school_detail.location}}</p>

    <h3>Students:</h3>

    {% for student in school_detail.students.all %}

      <!-- models.py related_name='students' -->

      <p>{{student.name}} who is {{student.age}} years old.</p>

    {% endfor %}

  </div>

{% endblock %}

 

# basic_app/templates/basic_app/school_list.html

 

{% extends "basic_app/basic_app_base.html" %}

 

{% block body_block %}

<h1>Welcome to a list of all the schools!</h1>

  <ol>

    <!-- Matching up to context_object_name in views.py -->

    {% for school in schools %}

      <h2><li><a href="{{school.id}}">{{school.name}}</a></li></h2>

    {% endfor %}

  </ol>

{% endblock %}

 

# urls.py

 

from django.contrib import admin

from django.urls import path, include

from basic_app import views

 

urlpatterns = [

    path('admin/', admin.site.urls),

    path('', views.IndexView.as_view()),

    path('basic_app/', include('basic_app.urls',namespace='basic_app'))

]

 

# basic_app/urls.py

 

from django.urls import path

from basic_app import views

 

app_name = 'basic_app'

 

urlpatterns = [

    path('', views.SchoolListView.as_view(), name='list'),

    path('<int:pk>/',views.SchoolDetailView.as_view(),name='detail'),

]

 

------------------

 

 

 

4. CRUD Views

- Create / Retrieve / Update / Delete

 

# basic_app/templates/basic_app/school_form.html

 

{% extends "basic_app/basic_app_base.html" %}

 

{% block body_block %}

 

<h1>

  {% if not form.instance.pk %}

  Create School

  {% else %}

  UpdateSchool

  {% endif %}

</h1>

 

  <form method="POST">

    {% csrf_token %}

    {{ form.as_p }}

    <input class="btn btn-primary"type="submit" name="" value="Submit">

  </form>

{% endblock %}

 

 

# basic_app/templates/basic_app/school_detail.html

 

{% extends 'basic_app/basic_app_base.html' %}

{% block body_block %}

  <div class="jumbotron">

    <h1>Welcome to the School Detail Page</h1>

    <h2>School details:</h2>

    <p>Name: {{school_detail.name}}</p>

    <p>Principal: {{school_detail.principal}}</p>

    <p>Location: {{school_detail.location}}</p>

    <h3>Students:</h3>

    {% for student in school_detail.students.all %}

      <!-- models.py related_name='students' -->

      <p>{{student.name}} who is {{student.age}} years old.</p>

    {% endfor %}

  </div>

  <div class="container">

    <p><a class="btn btn-warning" href="{% url 'basic_app:update' pk=school_detail.pk %}">Update</a></p>

  </div>

{% endblock %}

 

# basic_app/templates/basic_app/school_confirm_delete.html

 

{% extends "basic_app/basic_app_base.html" %}

 

{% block body_block %}

  <h1>Delete {{school.name}}?</h1>

  <form method="POST">

    {% csrf_token %}

    <input type="submit" class="btn btn-danger" value="Delete">

    <a href="{% url 'basic_app:detail' pk=school.pk %}">Cancel</a>

  </form>

{% endblock %}

 

# basic_app/urls.py

 

from django.urls import path

from basic_app import views

 

app_name = 'basic_app'

 

urlpatterns = [

    path('', views.SchoolListView.as_view(), name='list'),

    path('<int:pk>/',views.SchoolDetailView.as_view(),name='detail'),

    path('create/',views.SchoolCreateView.as_view(),name='create'),

    path('update/<int:pk>/',views.SchoolUpdateView.as_view(),name='update'),

    path('delete/<int:pk>/',views.SchoolDeleteView.as_view(),name='delete')

]

 

# models.py

 

from django.db import models

from django.urls import reverse

 

# Create your models here.

class School(models.Model):

    name = models.CharField(max_length=256)

    principal = models.CharField(max_length=256)

    location = models.CharField(max_length=256)

 

    def __str__(self):

        return self.name

 

    def get_absolute_url(self):

        return reverse("basic_app:detail", kwargs={'pk':self.pk})

 

class Student(models.Model):

    name = models.CharField(max_length=256)

    age = models.PositiveIntegerField()

    shcool = models.ForeignKey(School, related_name='students', on_delete=models.CASCADE)

 

    def __str__(self):

        return self.name

 

# views.py

 

from django.shortcuts import render

from django.urls import reverse_lazy

from django.views.generic import View, TemplateView, ListView, DetailView,CreateView, UpdateView, DeleteView

from . import models

 

class IndexView(TemplateView):

    template_name = 'index.html'

 

class SchoolListView(ListView):

    # my own context name

    context_object_name = 'schools'

    model = models.School

    # Automatically return school_list

 

 

class SchoolDetailView(DetailView):

    context_object_name = 'school_detail'

    # Automatically return school

    model = models.School

    template_name = 'basic_app/school_detail.html'

 

class SchoolCreateView(CreateView):

    fields = ('name', 'principal', 'location')

    model = models.School

 

class SchoolUpdateView(UpdateView):

    fields = ('name', 'principal')

    model = models.School

 

class SchoolDeleteView(DeleteView):

    model = models.School

    success_url = reverse_lazy("basic_app:list")

 

 

 

 

 

 

 

 

# When I tried to delete the added school, the pk number accumulated.

Ex) If I delete the 3, then I create new one. This one's pk starts from 4, not 3.

'개발 > Django' 카테고리의 다른 글

Django Deployment  (0) 2020.05.13
Login / Logout pages Implementation  (0) 2020.05.09
Templates - Relative URLs+ Inheritance + Filter  (0) 2020.05.07
장고 공부법  (0) 2020.05.07
Data List on the web page  (0) 2020.05.05
Comments