2016-03-06 123 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>