编辑视图不显示django中的选择字段数据?
问题描述:
这是用于编辑通过profile_edit视图的ModelForm代码:编辑视图不显示django中的选择字段数据?
models.py
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
city = models.CharField(default='kottayam', choices=CITY_CHOICES, max_length=150)
state = models.CharField(default='kerala', choices=STATE_CHOICES, max_length=150)
is_active = models.BooleanField()
def __unicode__(self):
return str(self.user)
forms.py
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
exclude = ['is_active']
views.py
def profile_edit(request):
profile, created = Profile.objects.get_or_create(user=request.user)
form = ProfileForm(request.POST or None, request.FILES or None, instance=profile)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
return redirect('profiles:profile', username=request.user.username)
context = {
"title": 'Edit Profile',
"form":form,
}
return render(request, 'profiles/form.html', context)
form.html
<form method='POST' action='' enctype='multipart/form-data' role="form">{% csrf_token %}
{{ form|crispy }}
<input type='submit' class='btn btn-success' value='Add/Edit Profile' />
</form>
Charfield与选择,情况是不可见的编辑,任何人都可以请帮助?
答
您需要更新ProfileForm您forms.py代码:
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('city', 'state')
CITY_CHOICES = your_city_choices # define your choices here.
STATE_CHOICES = your_state_choices
widgets = {
'city': forms.Select(choices=CITY_CHOICES),
'state': forms.Select(choices=STATE_CHOICES),
}
没有,它仍然是一样的,没有显示在编辑表单的选择领域。 – Biju