Django 我如何才能在模板中获得用户名与以下条件请告诉我?
我想知道我在下面的代码中没有发现错误,如果在e.html中有人能告诉我如何在下面的代码中获取用户的用户名。我的情况似乎不太好 /Django 我如何才能在模板中获得用户名与以下条件请告诉我?,django,django-forms,django-templates,django-template-filters,Django,Django Forms,Django Templates,Django Template Filters,我想知道我在下面的代码中没有发现错误,如果在e.html中有人能告诉我如何在下面的代码中获取用户的用户名。我的情况似乎不太好 / e.html <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {% if
e.html
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{% if request.user %}
<a class="navbar-brand" href="">Welcome{{request.user}}</a>
{% else %}
<a class="navbar-brand" href="">no</a>
{% endif %}
</a>
views.py
def registration_view(request):
# if this is a POST request we need to process the form data
template = 'home/login.html'
if request.method == 'POST':
print("post")
# create a form instance and populate it with data from the request:
form = RegisterForm(request.POST)
# check whether it's valid:
if form.is_valid():
print("okk valid")
if User.objects.filter(username=form.cleaned_data['username']).exists():
messages.error(request,'Username already exists')
return render(request, template, {
'form': form,
'error_message': 'Username already exists.'
})
elif User.objects.filter(email=form.cleaned_data['email']).exists():
messages.error(request,'Email already exists')
return render(request, template, {
'form': form,
'error_message': 'Email already exists.'
})
elif form.cleaned_data['password'] != form.cleaned_data['password_repeat']:
messages.error(request,'Password do not match ')
return render(request, template, {
'form': form,
'error_message': 'Passwords do not match.'
})
else:
# Create the user:
user = User.objects.create_user(
form.cleaned_data['username'],
form.cleaned_data['email'],
form.cleaned_data['password']
)
user.first_name = form.cleaned_data['first_name']
user.last_name = form.cleaned_data['last_name']
# user.date = form.cleaned_data['date']
print("save reached")
user.save()
# Login the user
login(request, user)
messages.success(request,"Created your account succcessfully in thumbsapp ")
return redirect('home')
您可以使用modelforms。您无需检查用户名或电子邮件是否存在,只需添加到您的模型:
unique=True.
要使用modelform添加新用户,请执行以下操作:
form.save()
您可以使用modelforms。您无需检查用户名或电子邮件是否存在,只需添加到您的模型:
unique=True.
要使用modelform添加新用户,请执行以下操作:
form.save()
e.html
{{request.user}}
返回用户对象,您可以使用{{request.user.username}
{code>{request.user.email}{code>{request.user.first_name}等访问所有用户参数
{{request.user}}
返回用户对象,您可以使用{{request.user.username}
{code>{request.user.email}{code>{request.user.first_name}访问所有用户参数等等我没有使用模型来创建帐户我没有使用模型来创建帐户我也尝试过,但没有获得用户对象你能告诉我为什么我没有通过请求获取用户名。用户,谢谢{%if request.User%}{%else%}{%endif%}我也试过了,但没有得到用户对象。你能告诉我为什么我不能通过request.User获得用户名吗?谢谢{%if request.User%}{%else%}{%endif%}