Dibidalidomba
Dibidalidomba

Reputation: 777

Form initial data does not display in template

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>

Upvotes: 4

Views: 1847

Answers (1)

Antoine Pinsard
Antoine Pinsard

Reputation: 35002

request.POST is an empty dict if no POST data were submitted. You must use request.POST or None, otherwise, it will be understood as "form submitted with every fields blank" and initialize won't be taken into account.

You also shouldn't call is_valid() on a form that was not submitted.

...
profile_form = MyForm(
    request.POST or None, instance=request.user.profile)
if request.method == 'POST' and profile_form.is_valid():
    ...

Upvotes: 3

Related Questions