Horai Nuri
Horai Nuri

Reputation: 5578

Django radio button value is not rendering

I created a radio field in my form, after registering the user I can't see what he checked.

user.html:

<p>{{ user.profile.name }}</p>
<p>{{ user.profile.email }}</p>
<p>{{ user.profile.choices }}</p> #not rendering anything, can't see the value after I logged in
<p>{{ user.choices }}</p> #(just in case) not rendering value

here is my code :

models.py:

class Profile(models.Model):
    user = models.OneToOneField(User)
    email = models.EmailField()
    name = models.CharField(max_length=20, blank=True, null=True)

forms.py

from utilisateur.models import Profile

class MyRegistrationForm(forms.ModelForm):
    CHOICES=[('clients','Je cherche une secretaire.'), ('secretaires','J\'offre mes services.')]
    choices = forms.ChoiceField(required=True, choices=CHOICES, widget=forms.RadioSelect())

    class Meta:
         model = Profile
         fields = ("name", "email", "choices")

    def save(self, commit=True):
        user = super(MyRegistrationForm, self).save(commit=False)
        user.choices = self.cleaned_data['choices']

        if commit:
            user.save()

        return user

What should I do in order the see the value of what I checked after I registered an user ? Am I doing something wrong ?

Upvotes: 0

Views: 297

Answers (1)

vsimkus
vsimkus

Reputation: 337

You seem to miss a choices field in your Profile class, therefore the profile does not get updated. Just try to add another char field in your Profile model:

choices = models.CharField(max_length=20, blank=True, null=True)

On the other hand, if you do not want choices to be permanently stored you can store it in the user session. For this you would have to update the MyRegistrationForm class:

class MyRegistrationForm(forms.ModelForm):
   CHOICES=[('clients','Je cherche une secretaire.'), ('secretaires','J\'offre mes services.')]
   choices = forms.ChoiceField(required=True, choices=CHOICES, widget=forms.RadioSelect())

   class Meta:
       model = Profile
       fields = ("name", "email")

   def save(self, commit=True):
       user = super(MyRegistrationForm, self).save(commit=False)
       ## In your session variable you create a field choices and store the user choice
       self.request.session.choices = self.cleaned_data['choices']

       if commit:
          user.save()
       return user

   def __init__(self, *args, **kwargs):
       ## Here you pass the request from your view
       self.request = kwargs.pop('request')
       super(MyRegistrationForm, self).__init__(*args, **kwargs)

Now, when you instantiate a MyRegistrationForm in View you should pass the request variable:

f = MyRegistrationForm(request=request)

With this, you can access the choices field in session variable until the user session closes. So in user.html you would display it as:

<p>{{ request.session.choices }}</p>

Upvotes: 2

Related Questions