编辑视图是不是在django中显示选择字段数据?

时间:2016-12-03 09:22:01

标签: django

这是通过profile_edit视图编辑ModelForm的代码:

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无法编辑,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您需要更新 ProfileForm 的form.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),
        }