취미삼아 배우는 프로그래밍

django - materialized css form 사용하기 본문

파이썬(장고)

django - materialized css form 사용하기

Nadure 2020. 3. 30. 21:25

장고의 기본 폼은 따로 명시하지 않는 이상, 그냥 일자로 쭉 나열된다

예를 들면 어드민페이지의 이것처럼?

 

때문에

div.row > div.col-s2-m4-l5

이런식으로 이 컴포넌트들의 div를 css framework로 잡아주려다 보면

폼을 일일히 새로 손으로 작성하게 된다.

 

실제로도 공홈에 소개돼 있기는 하다.

https://docs.djangoproject.com/en/3.0/topics/forms/#rendering-fields-manually

 

Working with forms | Django documentation | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com

{{ form.non_field_errors }}
<div class="fieldWrapper">
    {{ form.subject.errors }}
    <label for="{{ form.subject.id_for_label }}">Email subject:</label>
    {{ form.subject }}
</div>
<div class="fieldWrapper">
    {{ form.message.errors }}
    <label for="{{ form.message.id_for_label }}">Your message:</label>
    {{ form.message }}
</div>
<div class="fieldWrapper">
    {{ form.sender.errors }}
    <label for="{{ form.sender.id_for_label }}">Your email address:</label>
    {{ form.sender }}
</div>
<div class="fieldWrapper">
    {{ form.cc_myself.errors }}
    <label for="{{ form.cc_myself.id_for_label }}">CC yourself?</label>
    {{ form.cc_myself }}
</div>

 

 

이게.. 한 번만 작성하고 끝이라면 문제가 안되는데, 문제는 모델이 바뀌거나, 내용을 바꾸거나 함에 있어서

프론트엔드, 백엔드를 들락날락 거려야 하기 때문에 다소 헷갈리거나 어지러울 수 있다.

 

 

이거도 손코딩에서 벗어나게 해주는 앱이 있다.

장고는 진짜 뭐하면 다 있다..

 

이때 사용하는 것이 바로..

http://docs.viewflow.io/material_forms.html

 

Material Forms

Introduction Django-Material offers the alternative approach to rendering forms in django. Strong Python/HTML code separation keeps you code DRY and free from underline HTML/CSS rendering details. Field rendering customization happens in a template, not in

docs.viewflow.io

 

아주 잘 설명돼있다.

pip install django-material

 

폼셋 예제는

from django import forms
from django.forms import formset_factory
from material.forms import Form

class AddressForm(forms.Form):
    line_1 = forms.CharField(max_length=250)
    line_2 = forms.CharField(max_length=250)
    state = forms.CharField(max_length=100)
    city = forms.CharField(max_length=100)
    zipcode = forms.CharField(max_length=10)

    layout = Layout(
        'line_1',
        'line_2',
        'state',
        Row('city', 'zipcode'),
    )

AddressFormSet = formset_factory(AddressForm, extra=3, can_delete=True)


class SignupForm(Form):
    username = forms.CharField(max_length=50)
    first_name = forms.CharField(max_length=250)
    last_name = forms.CharField(max_length=250)
    emails = FormSetField(formset_class=EmailFormSet)
    addresses = FormSetField(formset_class=AddressFormSet)

    layout = Layout(
        'username',
        Row('first_name', 'last_name'),
        'emails',
        Stacked(1, 'addresses'),
    )

 

이렇게 이다.

layout을 통해 폼의 레이아웃을 잡아주고 이를 컨버팅 해주는 건데,

꽤나 신박하다.

class wall_detail_form(ModelForm):
    layout = Layout(
        Row('submitdate', 'final_date', 'is_it_16_floor',
            'is_it_BTF', 'addings_manufacturing', 'non_stnadard_area'),
        Row('creatings','coatings', 'salesman_name', 'drawing_designer'),
        'notes'

    )
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['submitdate'].widget.attrs.update({'class':'datepicker'})
        self.fields['final_date'].widget.attrs.update({'class':'datepicker'})
        self.fields['is_it_16_floor'].widget.attrs.update({'class':'m-checker'})
        self.fields['addings_manufacturing'].widget.attrs.update({'class':'m-checker'})
        self.fields['is_it_BTF'].widget.attrs.update({'class':'m-checker'})

    class Meta:
        model = wall_list_model
        exclude = ('standard_count','non_standard_coat_complete_chk',
                    'addings_complete_chk', 'non_standard_coat_complete_chk', 
                    'non_standard_manufacturing_chk', 'non_standard_outing_chk',
                    'standard_complete_chk', 'standard_go_to_location', 'nonstandard_go_to_location',
                    # 'addings_manufacturing',
                    'base_info', 'district_category',
                    )

 

나의 경우 위처럼 작성했는데,

이렇게 깔끔하게 나온다. 물론 체크아웃 부분은 CSS로 조금 위치를 수정해줘야 할 것 같긴 하다.

단점이라면 기존 모델폼처럼 뭐가 하나 추가되면 자동적으로 항목이 추가되지는 않는데,

그래도 레이아웃에 어떻게 들어가는지 적어두기만 하면 되니 크게 어려운건 아닌거 같다.

 

그 밖에 REST_API를 이용한 뷰 플로우를 생성하는 앱도 배포하고 있는듯 하다.

필요하면 써봐야지,,

 

 

 

 

Comments