Explore my side projects and work using this link

Upsidedown is a WordPress theme design that brings blog posts rising above inverted header and footer components.

Django model.forms 사용자 필드 추가

Written in

by

Advertisements

model form에서 추가로 별도의  사용자 필드를 추가하고 싶다면, 아래처럼 추가로 forms.필드타입 으로 선언해서 사용하면 된다.

label, widget 용례도 참고해 보면 좋다. required=False 도 옵션으로 주면, 필수 항목으로 추가 되지 않는다.

class FirmwareForm(forms.ModelForm):    is_fileinclue = "enctype=multipart/form-data"    autogen = forms.BooleanField(label=_("중복시 자동변경"), widget=forms.CheckboxInput(attrs={"class": "form-check-input", "type": "checkbox"}), required=False)        class Meta:        model = Firmware        fields = ["company", "dtype", "content"]        labels = {            "company": _("*회사"),            "dtype": _("타입"),            "content": _("파일"),        }        widgets = {            "company": forms.Select(attrs={"class": "form-select"}),            "dtype": forms.Select(attrs={"class": "form-select", "required": True, "placeholder": "타입"}),            # "content": forms.FileInput(attrs={"class": "form-control", "style":"width: 100px;"}),            # "content": forms.FileField('첨부 파일', upload_to='uploads/'),        }

사용할 때는 일반 필드와 동일하다.

if form.cleaned_data["autogen"]:

이런 식으로 값을 바로 보면 된다.

참고 사이트

예제 코드를 볼 수 있다. Django Forms BooleanField 예제 코드들

class CopyPermissionForm(forms.Form):    """    Holds the specific field for permissions    """    copy_permissions = forms.BooleanField(        label=_('Copy permissions'),        required=False,        initial=True,    )

django.forms BooleanField Python Code Examples
Python code examples to show how to use the BooleanField class within the forms module of the Django open source project.

Advertisements