개발/파이썬

장고 기본 양식 값 설정

맨날치킨 2022. 11. 26. 22:05
반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Django set default form values

장고 기본 양식 값 설정

 문제 내용 

I have a Model as follows:

다음과 같은 모델이 있습니다.

 

class TankJournal(models.Model):
    user = models.ForeignKey(User)
    tank = models.ForeignKey(TankProfile)
    ts = models.IntegerField(max_length=15)
    title = models.CharField(max_length=50)
    body = models.TextField()

I also have a model form for the above model as follows:

위 모델에 대한 모델 양식도 다음과 같이 가지고 있습니다.

 

class JournalForm(ModelForm):
    tank = forms.IntegerField(widget=forms.HiddenInput()) 

    class Meta:
        model = TankJournal
        exclude = ('user','ts')

I want to know how to set the default value for that tank hidden field. Here is my function to show/save the form so far:

나는 그 탱크 은닉 필드의 기본값을 설정하는 방법을 알고 싶다. 지금까지 양식을 표시/저장하는 기능은 다음과 같습니다.

 

def addJournal(request, id=0):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/')

    # checking if they own the tank
    from django.contrib.auth.models import User
    user = User.objects.get(pk=request.session['id'])

    if request.method == 'POST':
        form = JournalForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)

            # setting the user and ts
            from time import time
            obj.ts = int(time())
            obj.user = user

            obj.tank = TankProfile.objects.get(pk=form.cleaned_data['tank_id'])

            # saving the test
            obj.save()

    else:
        form = JournalForm()

    try:
        tank = TankProfile.objects.get(user=user, id=id)
    except TankProfile.DoesNotExist:
        return HttpResponseRedirect('/error/')

 

 

 높은 점수를 받은 Solution 

You can use Form.initial, which is explained here.

여기에 설명된 Form.initial을 사용할 수 있습니다.

 

You have two options either populate the value when calling form constructor:

폼 생성자를 호출할 때 값을 채우는 두 가지 옵션이 있습니다.

 

form = JournalForm(initial={'tank': 123})

or set the value in the form definition:

또는 양식 정의에서 값을 설정합니다.

 

tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123) 

 

 

 가장 최근 달린 Solution 

As explained in Django docs, initial is not default.

장고 문서에서 설명한 것처럼 이니셜은 기본값이 아닙니다.

 

  • The initial value of a field is intended to be displayed in an HTML . But if the user delete this value, and finally send back a blank value for this field, the initial value is lost. So you do not obtain what is expected by a default behaviour.
  • The default behaviour is : the value that validation process will take if data argument do not contain any value for the field.
필드의 초기 값은 HTML로 표시됩니다. 그러나 사용자가 이 값을 삭제하고 마지막으로 이 필드의 빈 값을 다시 보내면 초기 값이 손실됩니다. 따라서 기본 동작으로 예상되는 것을 얻을 수 없습니다. 기본 동작은 data 인수에 필드 값이 포함되지 않은 경우 유효성 검사 프로세스에서 취할 값입니다.

 

To implement that, a straightforward way is to combine initial and clean_<field>():

이를 구현하기 위해 간단한 방법은 initial과 clean_<field>()를 결합하는 것이다.

 

class JournalForm(ModelForm):
    tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123) 

    (...)

    def clean_tank(self):
        if not self['tank'].html_name in self.data:
            return self.fields['tank'].initial
        return self.cleaned_data['tank']

 

 

출처 : https://stackoverflow.com/questions/604266/django-set-default-form-values

반응형