반응형
CodingEntrepreneurs Django 강의 정리
delete.html>
{% extends "base.html" %}
{% block content %}
<h1>Are you sure you want to delete the following:</h1>
<p>{{ object.title }}</p>
<form method="POST"> {% csrf_token %}
<button class='btn btn-danger'>Yes, Delete</button>
</form>
{% endblock %}
views>
from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.decorators import staff_member_required
from django.http import Http404
from django.shortcuts import render, get_object_or_404, redirect
# Create your views here.
from .models import BlogPost
from .forms import BlogPostModelForm
# CRUD
# GET -> Retrieve / List
# POST -> Create / Update / DELETE
# Create Retrieve Update Delete
def blog_post_list_view(request):
# list out objects
# could be search
qs = BlogPost.objects.all() # queryset -> list of python object
template_name = "blog/list.html"
context = {"object_list": qs}
return render(request, template_name, context)
# @login_required(login_url="/login")
# @login_required
@staff_member_required
def blog_post_create_view(request):
# create objects
# ? use a form
# request.user > return something
# if not request.user.is_authenticated:
# return render(request, "note-a-user.html", {})
form = BlogPostModelForm(request.POST or None)
if form.is_valid():
obj = form.save(commit=False)
obj.user = request.user
# obj.title = form.cleaned_data.get("title") + "0"
obj.save()
form = BlogPostModelForm()
template_name = "form.html"
context = {"form": form}
return render(request, template_name, context)
def blog_post_detail_view(request, slug):
# 1 object -> detail view
obj = get_object_or_404(BlogPost, slug=slug)
template_name = "blog/detail.html"
context = {"object": obj}
return render(request, template_name, context)
@staff_member_required
def blog_post_update_view(request, slug):
obj = get_object_or_404(BlogPost, slug=slug)
form = BlogPostModelForm(request.POST or None, instance=obj)
if form.is_valid():
form.save()
template_name = "form.html"
context = {"form": form, "title": f"Update { obj.title }"}
return render(request, template_name, context)
@staff_member_required
def blog_post_delete_view(request, slug):
obj = get_object_or_404(BlogPost, slug=slug)
template_name = "blog/delete.html"
if request.method == "POST":
obj.delete()
return redirect("/blog")
context = {"object": obj}
return render(request, template_name, context)
반응형
'Python_WEB > Try_Django' 카테고리의 다른 글
[Django]Include the Navbar (0) | 2020.06.21 |
---|---|
[Django]Blog Post Navigation (0) | 2020.06.21 |
[Django]Better Validation on Update Views (0) | 2020.06.21 |
[Django]Update View with Model Form (0) | 2020.06.21 |
[Django]Logged In user & Forms (0) | 2020.06.21 |