[Answered ]-Initial data not working if I hide some one-to-many fields in django

1👍

Here is an approach I suggest (not tested though):

from django import forms

class ParentForm(ModelForm):
    agent = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))
    regcoord = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))
    provcoord = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))
    region = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))
    province = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(ParentForm, self).__init__(*args, **kwargs)

        self.fields['agent'].initial = self.user.agent
        self.fields['regcoord'].initial = self.user.regcoord
        self.fields['provcoord'].initial = self.user.provcoord
        self.fields['region'].initial = self.user.region
        self.fields['province'].initial = self.user.province

    class Meta:
        model = Adult
        fields = ['surname', 
            'first_name', 
            'other_name', 
            'address', 
            'dob', 
            'gender', 
            'id_no', 
            'receipt_no',
            'phone_no',
            'image'
         ]

Notes how I referenced the 5 fields (agent, regcoord, provcoord, region, province) as extra fields by declaring them as simple CharFields. So they are no longer rendered from the model as dropdown lists. Then in the method __init__ I define the initial values ​​for each of the fields.

Your function add_parent should become:

def add_parent(request,):

    form = ParentForm(user=request.user)

    if request.method == 'POST':
        form = ParentForm(request.POST, request.FILES,)
        if form.is_valid():
            form.save()
            return redirect('/')

    context = {'form' :form}
    return render(request, 'kyc/add_adult.html', context)

Edit

Here is another alternative:

def add_parent(request,):
    data = {'agent': request.user.agent, 'regcoord': request.user.regcoord, 'provcoord': request.user.provcoord, 'region': request.user.region, 'province': request.user.province}
    form = ParentForm(initial=data)

    if request.method == 'POST':
        form = ParentForm(request.POST, request.FILES,)
        if form.is_valid():
            form.save()
            return redirect('/')

    context = {'form' :form}
    return render(request, 'kyc/add_adult.html', context)

In the function add_parent, I pass the initial values ​​in the form of a dictionary (data), to the variable initial.

Then you need to remove the __init__ method from your form. Django will take care of rendering the form with the initial values ​​in the corresponding fields.

👤Tobin

Leave a comment