Meme's IT

[Django] view 함수 update 본문

BackEnd/Django

[Django] view 함수 update

Memez 2023. 10. 4. 14:05

HTTP request method(GET과 POST)를 이용해서 view 함수의 구조를 변경할 수 있다.

이전의 게시판 글을 쓸 때, 사용자 입력받는 페이지를 랜더링하는 new함수와 DB에 저장하는 create함수가 따로 있었는데

두개를 합쳐서 하나의 함수로 만들 수 있다.

 

# 이전의 new와 create함수를 합친 함수

def create(request):
    if request.method == "POST":	# POST방식이라면, 데이터 저장
        form = ArticleForm(request.POST)
        if form.is_valid():
            article = form.save()
            return redirect('article:detail',article.pk)
    else:
        form = ArticleForm()	# GET방식이라면 페이지 랜더링
    context = {
        'form' : form
    }
    return render(request, 'articles/create.html',context)

여기서 context에 담기는 form은

  1. is_valid를 통과하지 못해 에러메세지를 담은 form이거나
  2. else문을 통한 form 인스턴스

+ 추가 수정 요소

urls.py에서 사용하지 않는 new url은 제거

indexcreate html파일에 있는 url주소를 new → create로 변경

 

+ update와 edit함수도 동일한 방법으로 합칠 수 있다

'BackEnd > Django' 카테고리의 다른 글

[Django] 쿠키와 세션  (0) 2023.10.04
[Django] Static Files & Media Files  (0) 2023.10.04
[Django] ModelForm  (0) 2023.10.04
[Django] Form  (0) 2023.09.27
[Django] HTTP request methods  (0) 2023.09.26