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.

Advertisements

ModelForm init 함수에서 특정 필드값 초기값 주는 방법, 아래 글에 자세히 나와 있습니다.

Django set field value after a form is initialized

핵심은 initial 이라는 키워드

form.field["필드이름"].initial = 원하는값

이렇게 주면 된다.

많이들 아는 queryset 으로 Foreign Key로 연결된 테이블 값을 필터링 하는 방법은 많이 알고 있으니 머 생략하지만, 초기값을 막상 주려니 또 검색하게 되었다. 여기에 남겨둠

__init__ 오버라이딩 코드도 참고로 남겨둔다.

class ChooseProjectForm(forms.Form):    project = forms.ModelChoiceField(queryset=project_qs)    my_projects = forms.BooleanField()    def __init__(self, *args, **kwargs):        super(ChooseProjectForm, self).__init__(*args, **kwargs)        self.data = self.data.copy()  # IMPORTANT, self.data is immutable        # any condition:        if self.data.get('my_projects'):            my_projects = self.fields['project'].queryset.filter(my=True)            self.fields['project'].queryset = my_projects            self.fields['project'].initial = my_projects.first().pk            self.fields['project'].empty_label = None  # disable "-----"            self.data.update(project=my_projects.first().pk)  # Update Form data            self.fields['project'].widget = forms.HiddenInput()  # Hide if you want
  • empty_label – 빈 값 조정
  • forms.HiddenInput()
  • widget 지정

코드에서 이런 내용들을 살펴볼 수 있다. 공부하자!!

Advertisements