[Django] CheckBox 활용 Boolean 필드 핸들링

15065 단어 djangodjango

  • 목차

    -Model.Boolean 필드로 화면 출력 통제
    -CheckBox를 활용하여 Model.BooleanField 핸들링

Model.Boolean 값으로 화면 출력 통제

Class Post(models.Model):
	user_id = models.CharField(max_length = 50, default="")
    	postname = models.CharField(max_length = 50)
        content = models.TextField()
        important = models.BooleanField(default = True)

Model 필드에 BooleanField 형식의 필드를 추가합니다.
이 예제에서는 important라는 필드명을 사용했지만, 필드명은 다른 이름으로 사용해도 괜찮습니다.

(기존 Model에 새로운 필드를 추가하는 경우, 기존 Model 속 데이터들도 일괄적으로 변경됩니다. 새로운 필드에 값을 넣지 않을 경우, 에러가 발생하므로 Model에 새로운 필드를 추가할때는 default값을 지정하는것이 좋습니다.)

from.models import Post

def show_important_post(request):
	postlist = Post.objects.all()
    return render(request,'blog/Important_Posting.html',{'postlist':postlist})
postlist = Post.objects.all()

현재 생성된 Models의 Post를 import하고 현재 모델 Post속에 담겨있는 모든 objects들을 postlist에 담습니다.

return render(request,'blog/ImportantPost_Posting.html',{'postlist':postlist})

{'postlist':postlist}로 {key:value} 형식에 맞춰서 'blog/ImportantPost_Posting.html'에 넘깁니다.
(예시에서는 blog/ImportantPost_Posting.html에 넘겼지만 본인의 상황에 적합한 templates에 넘기면 됩니다.)

{% block contents %}
<h1>중요한 게시판 </h1>
{% for list in postlist %}
	{% if list.important is True %}
	<ul>
          	<li>
            		작성자: {{list.user_id}}
            		<a href = '/blog/showImportant/{{list.pk}}/">{{list.postname}'</a>
          	</li>
	</ul>
	{% endif %}
{% endfor %}
<button><a href = "/blog/ShowImportant/new_post/">글쓰기</a></button>
<input type = "button" value ="돌아가기" onclick = "back()">
{% endblock%}
                       
{{% for list in postlist %}}
	{{% if list.important is True %}}
{% endfor %}

앞서 views에서 넘겨 받은 postlist를 순회합니다. 만약 postlist에 해당하는 부분을 전부 출력하면 현재 가지고 있는 POST DB에 존재하는 모든 내용을 출력하게 됩니다. 하지만 저희는 if문을 활용하여 DB 속 모든 객체 들 중 important 필드의 값이 True인 경우만 li태그에 넣어 화면에 출력하도록 합니다.

{{list.postname}}

위 예제에서는 list의 postname필드를 출력했지만, list의 다른 필드를 출력해도 상관없습니다.



CheckBox활용 Model.BooleanField 핸들링

def edit _post(request,pk):
	post = Post.objects.get(pk=pk)
if request.method == 'POST':
	if len(request.POST.getlist('important')) ==0:
    		important = False
    	else: important = True
       	post.postname = request.POST['postname']
        post.content = request.POST['contents']
        post.important = important
        post.save()
post = Post.objects.get(pk=pk)

edit_post 함수를 통해 request 메시지와 (pk:primary key)를 받으면 Model class인 Post에서 pk가 동일한 객체를 찾아 post에 넘겨줍니다.

If len(request.POST.getlist('important'))==0:
	important = False
    else: important = True

'important'값은 체크박스를 통하여 값을 넘깁니다. 만약 위 예제 코드 속 다른 코드에서 쓰이는 것처럼 post.important = request.POST['important'] 형식을 사용하여 important값을 넣으려고 시도한다면 문제가 생깁니다. 체크 박스를 체크하여 request 요청했다면 문제가 되지 않지만, 체크 박스를 체크하지 않고 값을 넘기면 MultiValueDictKeyError 문제가 발생하기에 코드를 이와 같이 수정해야 합니다.

MultiValueDictKeyError를 피하기 위하여 우리는 important의 값을 list 형태로 가지고 옵니다. 만약 체크 박스를 체크했다면 list에 값이 들어있을 것이고 체크박스를 체크하지 않았다면 list에 값이 없을 것입니다. 그렇게 list의 길이를 len을 통해 측정하여 길이가 0이면 False를, 길이가 0이 아니면 True를 important 값에 넣어 post필드 값을 수정하여 save()해줍니다.

{% if Post.important is True %}
	<input type = "checkbox" name = "important" value ="True" checked> important <br>
{% else %}
	<input type = "checkbox" name = "important" value = "False"> important <br>
{% endif %}

Post의 필드 중 important 부분을 체크박스를 통하여 수정하는 templates의 일부를 가지고 왔습니다. 현재 Post의 important 부분이 True이면 체크된 상태로 화면에 출력되도록 하고 False이면 체크되지 않은 상태로 화면에 출력되도록 했습니다.

좋은 웹페이지 즐겨찾기