티스토리 뷰
#dojo/models.py
from django.db import models class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() user_agent = models.CharField(max_length=200) #추가 |
# dojo/forms.py
from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'content'] widgets = { # JavaScript로 브라우저 UserAgent정보를 담을 것이기에, 구지 UI에 노출할 필요가 없음. 'user_agent': forms.HiddenInput, # user_agent 필드 위젯 변경 } |
웹페이지 접속 후 개발자 도구를 통해 확인 가능
<input type="hidden" name="user_agent" id="id_user_agent">
기본 스타일로 렌더링
Form의 기본 제공 HTML Render
• form.as_table(), form.as_ul() form.as_p()
• str(form) 을 통해 .as_table() 함수 호출
<form action="" method="post"> {% csrf_token %} <legend>Post Form</legend> <table> {{ form.as_table }} </table> <input type="submit" /> </form> <script> /* 자바스크립트로 user_agent 필드값 채워넣기 */ var dom = document.getElementById('{{ form.user_agent.id_for_label }}'); dom.value = navigator.userAgent; </script> |
<input type="hidden" name="user_agent" id="id_user_agent" value="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36">
신규값 입력 후 admin 페이지 접근 후 데이터 확인 시 value값 입력
bootstrap3로 약간 멋내기 (https://getbootstrap.com/docs/3.3/css/)
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <div class='container'> <div class='row'> <div class='col-md-12'> <h1>Post Form</h1> <form action="" method="post"> {% csrf_token %} <table class='table table-hover table-bordered'> {{ form.as_table }} </table> <input type="submit" class="btn btn-primary" /> </form> </div> </div> </div> <script> var dom = document.getElementById('{{ form.user_agent.id_for_label }}'); dom.value = navigator.userAgent; </script> |
한땀한땀 직접 HTML 마크업하기
템플릿 Level 1 - 필드별로 하나하나 지정해 서 렌더링
<form action="" method="post"> <legend>Post Form</legend> {% csrf_token %} {% for error in form.non_field_errors %} <!-- non 필드 errors 목록 노출 --> {{ error }} {% endfor %} {{ form.user_agent }} <!-- 위젯 렌더링 --> <table> <tr> <td>{{ form.title.label_tag }}</td> <td> {{ form.title }} <!-- 위젯 렌더링 --> {{ form.title.help_text }} <!-- help_text 노출 --> {% for error in form.title.errors %} <!-- title errors 목록 노출 --> {{ erorr }} {% endfor %} </td> </tr> <tr> <td>{{ form.content.label_tag }}</td> <td> {{ form.content }} {{ form.content.help_text }} {% for error in form.content.errors %} {{ error }} {% endfor %} </td> </tr> </table> <input type="submit" /> </form> <script> /* 자바스크립트로 user_agent 필드값 채워넣기 */ var dom = document.getElementById('{{ form.user_agent.id_for_label }}'); dom.value = navigator.userAgent; </script> |
템플릿 Level 2 - 일괄적으로 렌더링 (비추)
<form action="" method="post"> <legend>Post Form</legend> {% csrf_token %} {% for error in form.non_field_errors %} {{ error }} {% endfor %} <!-- visible/hidden fields 모두 한 스타일로 렌더링 hidden fields에 대해서도 label_tag/help_text가 출력되기 때문에 비추 --> <table> {% for field in form %} <tr> <td>{{ field.label_tag }}</td> <td> {{ field }} {{ field.help_text }} {% for error in field.errors %} {{ error }} {% endfor %} </td> </tr> {% endfor %} </table> <input type="submit" /> </form> <script> var dom = document.getElementById('{{ form.user_agent.id_for_label }}'); dom.value = navigator.userAgent; </script> |
템플릿 Level 3 - visible/hidden 필드를 구분하여 렌더링 (추천) + 부트스트랩 적용
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <script src="//code.jquery.com/jquery-2.2.4.min.js"></script> <div class='container'> <div class='row'> <div class='col-md-12'> <h1>Post Form</h1> <form action="" method="post" class="form-horizontal"> {% csrf_token %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> {{ error }} </div> {% endfor %} {% for field in form.hidden_fields %} {{ field }} {% endfor %} {% for field in form.visible_fields %} <div class="form-group"> {{ field.label_tag }} <div class='col-sm-10'> {{ field }} {% if field.help_text %} <p class="help-block">{{ field.help_text }}</p> {% endif %} {% for error in field.errors %} <div class="alert alert-danger"> {{ error }} </div> {% endfor %} </div> </div> {% endfor %} <input type="submit" class="btn btn-primary" /> </form> </div> </div> </div> <script> $(function() { $('.form-group label').addClass('col-sm-2'); $('.form-group input, .form-group textarea').addClass('form-control'); }); var dom = document.getElementById('{{ form.user_agent.id_for_label }}'); dom.value = navigator.userAgent; </script> |
django-bootstrap3 팩키지
bootstrap3 스타일로 HTML을 생성해주는 template tags 제공 설치
쉘> pip3 install django-bootstrap3
settings.INSTALLED_APPS 에 "bootstrap3" 추가
Example) django-bootstrap3
{% load bootstrap3 %} {% bootstrap_css %} {% bootstrap_javascript %} <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <form action="" method="post"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" class="btn btn-primary" /> </form> </div> </div> </div> <script> $(function() { var dom = document.getElementById('{{ form.user_agent.id_for_label }}'); dom.value = navigator.userAgent; }); </script> |
Example) django-bootstrap3 (pagination)
# myapp/views.py from django.views.generic import ListView from .models import Post post_list = ListView.as_view(model=Post, paginate_by=10) {% load bootstrap3 staticfiles %} {% bootstrap_css %} {% bootstrap_javascript %} <table class="table table-bordered table-hover"> <caption>Post List</caption> <thead> <tr> <th>title</th> <th>created at</th> </tr> </thead> <tbody> {% for post in post_list %} <tr> <td>{{ post.title }}</td> <td>{{ post.updated_at }}</td> </tr> {% endfor %} </tbody> </table> <div class="text-center"> {% bootstrap_pagination page_obj %} </div> |
"""본 내용은 AskDjango VOD, "장고 차근차근 시작하기" 강의내용을 참고하여 작성했습니다.(https://nomade.kr/)"""
'Python > * Django' 카테고리의 다른 글
21. Messages Framework (0) | 2017.12.28 |
---|---|
19. ModelForm (0) | 2017.12.20 |
18. Form (0) | 2017.12.19 |
17. HttpRequest and HttpResponse (0) | 2017.12.18 |
16. CSRF(Cross-Site Request Forgery) (0) | 2017.12.15 |