Form initial data does not display in template

Viewed 1550

I have a form with some fields that have initial values. After run my application, the form appears but its fields initial values don't display, just an empty form.

I put a {{ profile_form.initial }} in my template to make sure that the form has initial data. It returns a dict with initial data:

{'local_number': 'test-local-number', 'last_name': 'test-last-name', 'phone': 'test-phone', 'zip_code': 'test-zip-code', 'city': 'test-city', 'user': <User: testuser>, 'street': 'test-street', 'first_name': 'test-first-name'}

Here is my code:

forms.py

class MyForm(forms.ModelForm):
    initial_fields = ['first_name', 'last_name', 'phone', 'street',
                      'local_number', 'city', 'zip_code']
    class Meta:
        model = UserProfile
        fields = ('first_name', 'last_name', 'phone', 'street',
                  'local_number', 'city', 'zip_code')

    def __init__(self, *args, **kwargs):
        self.instance = kwargs.pop('instance', None)
        initial = kwargs.pop('initial', {})
        for key in self.initial_fields:
            if hasattr(self.instance, key):
                initial[key] = initial.get(key) or getattr(self.instance, key)
        kwargs['initial'] = initial
        super(MyForm, self).__init__(*args, **kwargs)

views.py

def my_view(request):
    context = {}
    if request.user.is_authenticated():
        profile_form = MyForm(
            request.POST, instance=request.user.profile)
        if profile_form.is_valid():
            profile_form.save()
        context.update({'profile_form': profile_form})
        }
        return render(request, 'template.html', context)

template.html

<form class="animated-form" action="" method="POST">
    {% csrf_token %}
    {{ profile_form.initial }}
    {{ profile_form.as_p }}
    <div>
        <div class="row">
            <div class="col-lg-12 text-center">
                <button type="submit">Submit</button> 
            </div>
        </div> 
    </div>
</form>
1 Answers
Related