from django import formsfrom.models import ArticleclassArticleForm(forms.ModelForm): title = forms.CharField( max_length=100, label='Title', help_text='Your title must be no more than 100 characters in length', widget=forms.TextInput( attrs={'class':'my_input','placeholder': "What's on your mind?" } ) ) content = forms.CharField( label='Content', help_text='Jot down random musings and thoughts', widget=forms.Textarea( attrs={'row':5,'col':50, } ) )classMeta: model = Article# ๋ค ๋๋ ค๋ฐ์ fields ='__all__'
View์์ ModelFrom ํ์ฉ
view.py
from django.shortcuts import render, redirect, get_object_or_404from django.views.decorators.http import require_POSTfrom.models import Articlefrom.forms import ArticleForm# Create your views here.defindex(request): articles = Article.objects.order_by('-pk') context ={'articles': articles}returnrender(request, 'articles/index.html', context)defcreate(request):# POST /articles/create/if request.method =='POST':# Article table์ data๋ฅผ ์ ์ฅํจ form =ArticleForm(request.POST)if form.is_valid(): form.save()#detail๋ก redirectreturnredirect('articles:index')print('errors?',form.errors)print('cleaned_data?',form.cleaned_data)# GET /articles/create else:# ๋น ๊ป๋ฐ๊ธฐ input form form =ArticleForm() context ={'form': form,}returnrender(request, 'articles/form.html', context)defdetail(request,pk): article =get_object_or_404(Article, id=pk) context ={'article':article}returnrender(request, 'articles/detail.html', context)@require_POSTdefdelete(request,pk): article =get_object_or_404(Article, id=pk) article.delete()returnredirect('articles:index')defupdate(request,pk): article =get_object_or_404(Article, id=pk)if request.method =='POST': form =ArticleForm(request.POST,instance=article)if form.is_valid(): article = form.save()returnredirect('articles:detail', article.pk)else: form =ArticleForm(instance=article) context ={'form':form}returnrender(request, 'articles/form.html', context)
{% if request.resolver_match.url_name == 'create' %}
<h2>Write a post</h2>
{% else %}
<h2>Edit post</h2>
{% endif %}
loop or bootstrap4 ํ์ฉํ์ฌ ์ถ๋ ฅํ๊ธฐ
form.html
{% extends 'base.html' %}
{% load bootstrap4 %}
{% block body %}
{% if request.resolver_match.url_name == 'create' %}
<h2>Write a post</h2>
{% else %}
<h2>Edit post</h2>
{% endif %}
<!-- loop ํ์ฉ-->
<form action="" method="POST">
{% csrf_token %}
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} <br>
{{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
<input type="submit" value="Submit">
</form>
<!-- bootstrap4 ์ฌ์ฉ -->
<form action="" method="POST">
{% csrf_token %}
{% bootstrap_form form %}
<button class="btn btn-primary"> Submit</button>
</form>
{% endblock %}
shell ๋ค์ด๊ฐ๊ธฐ
$pythonmanage.pyshell_plus
shell
In [1]: from articles.forms import ArticleForm
In [2]: form = ArticleForm()
In [3]: form
Out[3]: <ArticleForm bound=False, valid=Unknown, fields=(title;content)>