2016-03-06 85 views
0

我在我的表单中创建了一个广播字段,注册用户后我看不到他检查的内容。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 

我应该怎么做才能看到我注册用户后检查的值?难道我做错了什么 ?

回答

2

您似乎错过了Profile类中的choices字段,因此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) 

现在,当你在View实例化一个MyRegistrationForm你应该通过request变量:

f = MyRegistrationForm(request=request) 

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

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