Django单选按钮值不呈现

时间:2016-03-06 10:46:18

标签: python django

我在我的表单中创建了一个无线电字段,在注册用户后我无法看到他检查的内容。

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

这是我的代码:

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

为了看到我在注册用户后查看的内容的价值,我该怎么做?我做错了吗?

1 个答案:

答案 0 :(得分:2)

您似乎错过了choices课程中的Profile字段,因此profile未获得更新。只需尝试在Profile模型中添加另一个字段:

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

另一方面,如果您不希望永久存储choices,则可以将其存储在用户session中。为此,您必须更新MyRegistrationForm类:

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)

现在,当您在MyRegistrationForm中实例化View时,您应该传递request变量:

f = MyRegistrationForm(request=request)

有了这个,您可以访问session变量中的choices字段,直到用户session关闭。因此,在 user.html 中,您会将其显示为:

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