Form and ModelForm

.order_by()

pk ์—ญ์ˆœ์œผ๋กœ ์ •๋ ฌ

articles = Article.objects.order_by('-pk')

ModelForm

ModelForm ์ •์˜ํ•˜๊ธฐ

forms.py

from django import forms
from .models import Article

class ArticleForm(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,
            }
        )
    )
    class Meta:
        model = Article
        # ๋‹ค ๋•Œ๋ ค๋ฐ•์•„
        fields = '__all__'

View์—์„œ ModelFrom ํ™œ์šฉ

view.py

request.resolver_match.url_name ์œผ๋กœ ์กฐ๊ฑด์— ๋”ฐ๋ฅธ ์ฒ˜๋ฆฌ

form.html

  • ๋ถ„๊ธฐ์˜ ๊ธฐ์ค€์€ url_name ์ด๋‹ค

  • path๋กœ ํ•˜๋ฉด, url์ด ๋ฐ”๋€” ๋•Œ๋งˆ๋‹ค ๋ฐ”๊ฟ”์ค˜์•ผ ํ•œ๋‹ค!

loop or bootstrap4 ํ™œ์šฉํ•˜์—ฌ ์ถœ๋ ฅํ•˜๊ธฐ

form.html

shell ๋“ค์–ด๊ฐ€๊ธฐ

shell

p tag ๋กœ ์ด๋ฃจ์–ด์ง„ input๋“ค์˜ ์ง‘ํ•ฉ

table๋กœ ์ด๋ฃจ์–ด์ง„ input๋“ค์˜ ์ง‘ํ•ฉ

Looping over the formโ€™s fields

If youโ€™re using the same HTML for each of your form fields, you can reduce duplicate code by looping through each field in turn using a `

` loop:

Form rendering options

There are other output options though for the / pairs:

  • {{ form.as_table }} will render them as table cells wrapped in tags

  • {{ form.as_p }} will render them wrapped in `` tags

  • {{ form.as_ul }} will render them wrapped in `` tags

Note that youโ€™ll have to provide the surrounding or elements yourself.

Hereโ€™s the output of {{ form.as_p }} for our ContactForm instance:

Django Bootstrap ์‚ฌ์šฉํ•˜๊ธฐ

Install

settings.py ์ˆ˜์ •

base.html์— bootstrap ์‚ฌ์šฉํ• ๊ฑฐ๋ผ๊ณ  ์„ ์–ธ

detail.html - bootstrap ์ ์šฉ๋˜๋Š” template๋“ค์—๋„ ์„ ์–ธ

+

Git

ํŠน์ • commit์„ ๊ธฐ์ค€์œผ๋กœ ๋Œ์•„๊ฐ€๊ธฐ

test branch ๋งŒ๋“ค๋ฉด์„œ ์ด๋™ํ•˜๊ธฐ

reference log ํ™•์ธ

์–ด๋””์— head ์žˆ๋Š”์ง€ ํ™•์ธ

๋‹ค์‹œ test branch๋กœ ๋Œ์•„๊ฐ€๊ธฐ

Last updated

Was this helpful?