我正在尝试显示我的用户信息,但我将匿名用户作为我的输出; Anonymous User
我的views.py中的代码如下;
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/account')
else:
form = RegistrationForm()
args = {'form' : form}
return render(request, 'accounts/register.html', args)
def view_profile(request):
args = {'user': request.user}
return render (request, 'accounts/profile.html',args)
我在使用UserCreationForm,我在forms.py中的代码是;
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = {
'username',
'first_name',
'last_name',
'email',
'password1',
'password2'
}
def save(self,commit=True):
user = super(RegistrationForm,self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
我希望显示个人资料信息的profile.html是
{% block head %}
<title> User Profile </title>
{% endblock %}
{% block body %}
<div class="container">
<p>
<h1> {{user}}</h1>
<h3>First Name: {{user.first_name}}</h3>
<h3>Last Name: {{user.last_name}}</h3>
<h3>Email: {{user.email}}</h3>
</p>
</div>
{% endblock %}
真的不确定我哪里出错了,非常感谢任何帮助。
答案 0 :(得分:2)
您必须使用@login_required装饰def view_profile(request):
,否则Django也会向匿名用户提供此请求。
另请注意,如果您django.core.context_processors.request
拥有(或添加)settings.TEMPLATE_CONTEXT_PROCESSORS
(或settings.TEMPLATES['OPTIONS']['context_processors']
取决于您的django版本)您可以在模板中使用{{request.user}}
,而无需在上下文中创建特定条目。