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