ModelForm的用法,一个页面多个ModelForm

 

calories隐含字段,通过计算得出的例子

from django import forms
from .models import Nutrient

class NutrientForm(forms.ModelForm):
    name = forms.CharField(label='食品名', max_length=255, required=True)
    calories = forms.IntegerField(label='カロリー', widget=forms.HiddenInput, required=False)
    protein = forms.IntegerField(label='タンパク質', required=True)
    fat = forms.IntegerField(label='脂質', required=True)
    carbohydrate = forms.IntegerField(label='炭水化物', required=True)

    class Meta:
        model = Nutrient
        fields = ['name', 'calories', 'protein', 'fat', 'carbohydrate']

    def clean(self):
        cleaned_data = super().clean()
        protein = cleaned_data.get('protein')
        fat = cleaned_data.get('fat')
        carbohydrate = cleaned_data.get('carbohydrate')
        if protein is None or fat is None or carbohydrate is None:
            raise forms.ValidationError('タンパク質、脂質、炭水化物は必須です。')
        else:
            calories = protein * 4 + fat * 9 + carbohydrate * 4
            cleaned_data['calories'] = calories
        return cleaned_data

 

 

class testView(View):

    def get(self, request, *args, **kwargs):

        #複数のフォームをコンテキストとして渡す
        context = {
            'main_form' : Test1ModelForm(),
            'detail_form' : Test2ModelForm(),
        }
    
        return TemplateResponse(request, 'test.html', context)

    def post(self, request, *args, **kwargs):
        form1 = Test1ModelForm(request.POST)
        form2 = Test2ModelForm(request.POST)

        #全てのフォームのvalidationが通ったらsave
        if form1.is_valid() and form2.is_valid():
            form1.save()
            form2.save()
        
        return HttpResponseRedirect(reverse('test'))

 

template.html

<form method="post">
    {% csrf_token %}
        <table>
            {{ main_form.as_table }}
        </table>
        <br>

        <table>
            {{ detail_form.as_table }}
        </table>

    <input type="submit" value="登録">
</form>

 

posted @ 2023-07-10 09:59  花生与酒  阅读(27)  评论(0编辑  收藏  举报