def new(request):
return render(request, 'new.html')
def create(request):
new_blog = Blog()
new_blog.title = request.POST['title']
new_blog.writer = request.POST['writer']
new_blog.body = request.POST['body']
new_blog.pub_date = timezone.now()
new_blog.save()
# 새로 생성한 detail로 이동(id값 이용해서)
return redirect('detail', new_blog.id)
HTML에 Blog객체를 찍어내어 데이터를 웹페이지 상에서 볼 수 있도록 하는 것
home() : 맨 처음 홈 화면을 보여주는 메서드
def home(request):
# home함수가 모든 블로그 객체를 보냄
blogs = Blog.objects.all()
paginator = Paginator(blogs, 3)
# .get()을 하면 정보가 오지 않아도 넘어감
page = request.GET.get('page')
blogs = paginator.get_page(page)
return render(request, 'home.html', {'blogs': blogs})
def detail(request, id):
blog = get_object_or_404(Blog, pk = id)
return render(request, 'detail.html', {'blog':blog})
Create과 거의 유사하지만 Update는 수정할 데이터의 id를 받아야 한다는 특징이 있음!
- views.py에서 매개변수를 받아 사용하고 싶다면
urls.py
에서 path converter(<str:id>)를 사용해야 함!edit.html
에서도 < form action="{%url 'update' blog.id %}" method="post" >처럼 넘겨줄 인자로 id를 명시해야 함! edit() : edit.html을 보여주는 메서드
def edit(request, id):
edit_blog = Blog.objects.get(id=id)
return render(request, 'edit.html', {'blog': edit_blog})
def update(request, id):
update_blog = Blog.objects.get(id=id)
update_blog.title = request.POST['title']
update_blog.writer = request.POST['writer']
update_blog.body = request.POST['body']
update_blog.pub_date = timezone.now()
update_blog.save() # 빼먹으면 데이터베이스에 수정이 안됨!
return redirect('detail', update_blog.id)
urls.py
에서 path converter(<str:id>)를 사용detail.html
에서 < a href="{% url 'delete' blog.id %}">삭제하기< /a >처럼 넘겨줄 인자로 id명시def delete(request, id):
delete_blog = Blog.objects.get(id=id)
delete_blog.delete()
return redirect('home')