Please help me, when first loading the form, in the form fields, to display data from the database.

models:

class Status(models.Model): status = models.CharField(max_length=40, blank=False, ) @classmethod def get_status_list(self): status_list = list() status_list.append(('', 'Не указан')) for values_ins in Status.objects.all().values_list('id', 'status'): status_list.append(values_ins) return status_list class UserProfile(User): name1 = models.CharField('Имя', max_length=30, blank=True, null=True, ) name2 = models.CharField('Отчество', max_length=30, blank=True, null=True, ) status = models.ForeignKey(Status, verbose_name='Статус', blank=True, null=True, ) 

forms:

 class PersonalDataForm(forms.ModelForm): status = forms.ChoiceField(widget=forms.Select, choices=Status.get_status_list(),label='Статус',required=False, ) class Meta: model = UserProfile fields = ('name1', 'name2', ) 

views:

 @login_required def personal_data_page(request): entry_user_profile = UserProfile.objects.get(user_ptr_id=request.user.id) form = PersonalDataForm(instance=entry_user_profile) if request.method == 'POST': form = PersonalDataForm(request.POST, instance=entry_user_profile) if form.is_valid(): form.save() entry_user_profile.save() return HttpResponseRedirect('/userprofile/personal_data_page_changed/') t = loader.get_template('personal_data_page.html') c = RequestContext(request, {'form': form,}) return HttpResponse(t.render(c)) 

template:

 {{ form.name1 }} {{ form.name2 }} {{ form.status }} 

the problem is that when the form is first loaded, the user sees data from the database in the fields: "name1", "name2". but does not see data from the database in the "status" field (the item "not specified" is shown there, although the item corresponding to the value in the status_id field of the UserProfile table should be shown)

I need to specify a specific value in the "status" field when the form is first loaded. help me please

    2 answers 2

    Remove the get_status_list method.

    In the shape of:

     status = UserProfile._meta.get_field('status').formfield(empty_label=u'Не указан', required=False) 

    This way you will get a real status field of the form, which will be filled with initialization data.

      Emmm, why do you describe the status field in your form manually, also with crutches? If something goes wrong with you - you shouldn’t immediately support props, it’s better to figure out if you understood everything correctly and whether it’s really not done by regular means, then look for a ready-made solution, and only if there are no ready-made solutions or they don’t fit, build his