pythonApp\class_crud\class_crud\class_crud\urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('books/', include('books.urls')),
]
pythonApp\class_crud\class_crud\books\urls.py
from django.urls import path
from . import views
from books.views import BooksListView, BooksCreateView, BooksDetailView, BooksUpdateview, BooksDeleteView, BooksSearchView
app_name = 'books'
urlpatterns = [
# path("", views.IndexView.as_view(), name="index"),
path("", BooksListView.as_view(), name="list"),
path("create", BooksCreateView.as_view(), name="create"),
path('show/', BooksDetailView.as_view(), name='show'),
path('update/', BooksUpdateview.as_view(), name='update'),
path('delete/', BooksDeleteView.as_view(), name='delete'),
path('search', BooksSearchView.as_view(), name='search'),
]
pythonApp\class_crud\class_crud\books\views.py
from django.views.generic import TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView, FormView
from django.views.generic.edit import ModelFormMixin
from .models import Books
from .forms import BooksForm
from .forms import BooksSearchForm
from django.urls import reverse_lazy
from django.shortcuts import render
from django.shortcuts import render
class IndexView(TemplateView):
template_name = "books/index.html"
class BooksListView(ListView):
model = Books
template_name = 'books/list.html'
form_class = BooksSearchForm
success_url = reverse_lazy('books:list')
paginate_by = 5
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs) # はじめに継承元のメソッドを呼び出す
context["form"] = BooksSearchForm
return context
def post(self, request):
txt = request.POST['find']
params = {
'form': BooksSearchForm,
'books_list': Books.objects.filter(title=txt)
}
return render(request, 'books/list.html', params)
def get(self, request, *args, **kwargs):
self.object = None
return super().get(request, *args, **kwargs)
class BooksCreateView(CreateView):
model = Books
form_class = BooksForm
template_name = 'books/create.html'
success_url = reverse_lazy('books:list')
class BooksDetailView(DetailView):
model = Books
template_name = 'books/show.html'
class BooksUpdateview(UpdateView):
model = Books
form_class = BooksForm
template_name = 'books/update.html'
success_url = reverse_lazy('books:list')
class BooksDeleteView(DeleteView):
model = Books
template_name = 'books/delete.html'
success_url = reverse_lazy('books:list')
class BooksSearchView(FormView):
template_name = 'books/list.html'
paginate_by = 5
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form'] = BooksSearchForm(self.request.GET)
return context