Django - 将值从表单传递给模型

时间:2013-11-07 20:15:12

标签: python django django-models django-forms django-views

我正在使用Django表单模块获取值并将其传递给用户配置文件。 唯一的问题是home_type是一个“forms.ChoiceField”但是form.ChoiceField没有“clean_data”类型,那么如何获得无线电选择值并将其传递给用户配置文件模块?

模块的代码是这样的:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(max_length=30, blank=True)
    productNo = models.CharField(max_length=50, blank=True)
    location = models.CharField(max_length=50, blank=True)
    average_temp = models.CharField(max_length=5, blank=True)

    HOME_TYPE = (
        ('AP', 'Apartment/Condo'),
        ('SH', 'Single House/Residential'),
        ('ST', 'Studio'),
        ('TH', 'Townhouse'),
        ('MH', 'Moblie Home'),
    )

    home_type = models.CharField(max_length=1, choices=HOME_TYPE)

和表格代码:

class UserProfileForm(forms.Form):
    name = forms.CharField(label="Name", max_length=30, widget=forms.TextInput(attrs={'size':     20,}))
    productNo = forms.CharField(label="ProductNo", max_length=50, widget=forms.TextInput(attrs={'size': 20,}))
    location = forms.CharField(label="Location", max_length=50, widget=forms.TextInput(attrs={'size': 20,}))
    average_temp = forms.CharField(label="Average_Temp", max_length=10, widget=forms.TextInput(attrs={'size': 20,}))

    HOME_TYPE = (
        ('AP', 'Apartment/Condo'),
        ('SH', 'Single House/Residential'),
        ('ST', 'Studio'),
        ('TH', 'Townhouse'),
        ('MH', 'Moblie Home'),
    )

    home_type = forms.ChoiceField(label="home_type", widget=forms.RadioSelect(), choices=HOME_TYPE)

在我的view.py中,处理值传递的代码是:

def user_profile_update(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/keenhome/accounts/login/')
    UserProfile = request.user.get_profile()
    if request.method == 'POST':
        form=UserProfileForm(request.POST)
        if form.is_valid():
            UserProfile.name = form.cleaned_data["name"]
            UserProfile.productNo = form.cleaned_data["productNo"]
            UserProfile.location = form.cleaned_data["location"]
            UserProfile.average_temp = form.cleaned_data["average_temp"]

            #problem happens here:
            UserProfile.home_type = form.cleaned_data["home_type"]

            UserProfile.save()
            return HttpResponseRedirect('/keenhome/accounts/user_profile/')
        else:
            form = UserProfileForm()      
            return render_to_response("polls/user_profile_update.html", {'form':form}, context_instance=RequestContext(request))

    else:
        form = UserProfileForm()
        return render_to_response("polls/user_profile_update.html", {'form':form}, context_instance=RequestContext(request))

唯一的问题是forms.ChoiceField没有“clean_data”类型,那么如何获取无线电选择值并将其传递给用户配置文件模块?

3 个答案:

答案 0 :(得分:2)

您无需再次编写表单的所有字段。这就是它被称为ModelForm的原因,它应该从模型中自动生成:

HOME_TYPE = (
    ('AP', 'Apartment/Condo'),
    ('SH', 'Single House/Residential'),
    ('ST', 'Studio'),
    ('TH', 'Townhouse'),
    ('MH', 'Moblie Home'),
)

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(max_length=30, blank=True)
    productNo = models.CharField(max_length=50, blank=True)
    location = models.CharField(max_length=50, blank=True)
    average_temp = models.CharField(max_length=5, blank=True)
    home_type = models.CharField(max_length=2, choices=HOME_TYPE)

forms.py:

class UserProfileForm(ModelForm):
   class Meta:
       model = UserProfile
       exclude = (user,)

views.py:

def user_profile_update(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/keenhome/accounts/login/')
    form = UserProfileForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            form.user = request.user
            form.save()
            return HttpResponseRedirect('/keenhome/accounts/user_profile/')
    return render_to_response("polls/user_profile_update.html", {'form':form}, context_instance=RequestContext(request))

修改:   使得max_length = 2,感谢@ndpu,排除了用户,在表单中添加了用户保存,感谢@void

答案 1 :(得分:1)

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    .....


class UserProfileForm(ModelForm):
    pass
    class Meta:
        model = UserProfile
        exclude = (user,) # you need to exclude user

现在所有这些代码......:

def user_profile_update(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/keenhome/accounts/login/')
    UserProfile = request.user.get_profile()
    if request.method == 'POST':
        form=UserProfileForm(request.POST)
        if form.is_valid():
            UserProfile.name = form.cleaned_data["name"]
            UserProfile.productNo = form.cleaned_data["productNo"]
            UserProfile.location = form.cleaned_data["location"]
            UserProfile.average_temp = form.cleaned_data["average_temp"]

            #problem happens here:
            UserProfile.home_type = form.cleaned_data["home_type"]

            UserProfile.save()
            return HttpResponseRedirect('/keenhome/accounts/user_profile/')
        else:
            form = UserProfileForm()      
            return render_to_response("polls/user_profile_update.html", {'form':form}, context_instance=RequestContext(request))

    else:
        form = UserProfileForm()
        return render_to_response("polls/user_profile_update.html", {'form':form}, context_instance=RequestContext(request))

会变成:

def user_profile_update(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/keenhome/accounts/login/')

    form = UserProfileForm(request.POST or None)

    if form.is_valid():
        form = form.save(commit=False) 
        form.user = request.user# because user is excluded
        form.save()
        #code
    else:
        #code

    return render_to_response("polls/user_profile_update.html", {'form':form}, context_instance=RequestContext(request))

答案 2 :(得分:1)

我认为问题在于:

class UserProfile(models.Model):
    #...
    home_type = models.CharField(max_length=1, choices=HOME_TYPE)

应为max_length=2

    home_type = models.CharField(max_length=2, choices=HOME_TYPE)