我在我的表单中创建了一个无线电字段,在注册用户后我无法看到他检查的内容。
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
为了看到我在注册用户后查看的内容的价值,我该怎么做?我做错了吗?
答案 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>