noben
noben

Reputation: 561

Django - pass a value from form to model

i am using Django form module to get value and pass it to user profile. The only problem is that the home_type is a "forms.ChoiceField" but there is no "clean_data" type for the forms.ChoiceField, so how can i get the radio select value and pass it to the user profile module?

the code of module is like this:

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)

and the code of form:

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)

In my view.py, the code to deal with the value passing is:

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))

The only problem is that there is no "clean_data" type for the forms.ChoiceField, so how can i get the radio select value and pass it to the user profile module?

Upvotes: 1

Views: 3585

Answers (3)

user1301404
user1301404

Reputation:

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


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

Now all of this code...:

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))

would have become:

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))

Upvotes: 1

ndpu
ndpu

Reputation: 22571

I think the problem is here:

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

should be max_length=2:

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

Upvotes: 1

nickzam
nickzam

Reputation: 813

You don't need to write all fields of form again. That's why it's called ModelForm, it should be auto-generated from model:

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))

EDIT: made max_length = 2, thanks @ndpu, excluded user, added user saving in form, thanks @void

Upvotes: 2

Related Questions