[모각코][210804] Django Blog 예제 - View 구현

Jinhyung Rhee·2021년 8월 4일
0
post-thumbnail

View

  • 데이터를 처리하는 곳
  • CRUD 처리를 views.py에서 구현

Create

  • new() : new.html을 보여주는 메서드
def new(request):
	return render(request, 'new.html')
  • create() : new.html에서 받은 정보를 데이터베이스에 저장하는 메서드
    - redirect() : 요청이 보내졌을 때 어떤 화면으로 이동할 것인지를 결정
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)

Read

  • 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})
  • detail() : 글을 클릭하여 '자세히 보기' 기능을 하는 메서드
    - get_object_or_404() :객체가 존재할 경우 가져오고 없으면 404에러 리턴
def detail(request, id):
  blog = get_object_or_404(Blog, pk = id)
  return render(request, 'detail.html', {'blog':blog})

Update

  • 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})
  • update() : 수정한 내용을 데이터베이스에 적용하는 메서드
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)

Delete

  • Delete도 Update처럼 삭제할 데이터의 id를 받아야 함!
    - views.py에서 매개변수를 받아서 사용하기 위해
    • urls.py에서 path converter(<str:id>)를 사용
    • detail.html에서 < a href="{% url 'delete' blog.id %}">삭제하기< /a >처럼 넘겨줄 인자로 id명시
  • delete() : 전달받은 id값에 해당하는 데이터 하나를 삭제하는 메서드
def delete(request, id):
    delete_blog = Blog.objects.get(id=id)
    delete_blog.delete()
    return redirect('home')
profile
기록하는 습관

0개의 댓글