python - Form initial data does not display in template -


i have form fields have initial values. after run application, form appears fields initial values don't display, empty form.

i put {{ profile_form.initial }} in template make sure form has initial data. returns dict 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 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', {})         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> 

request.post empty dict if no post data submitted. must use request.post or none, otherwise, understood "form submitted every fields blank" , initialize won't taken account.

you shouldn't call is_valid() on form not submitted.

... profile_form = myform(     request.post or none, instance=request.user.profile) if request.method == 'post' , profile_form.is_valid():     ... 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -