我如何获得用户名

问题描述 投票:0回答:1

你能告诉我任何人如何从用户那里获取用户名吗。因为我的条件在下面的代码中不起作用/......................。 ................................................... ...............................

e.html
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Welcome  {{request.user}}

        </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')
django django-forms django-templates django-template-filters
1个回答
0
投票

您可以使用模型形式。而且您不需要检查用户名或电子邮件是否存在,只需添加

     unique=True.

使用modelform添加新用户:

   form.save()
© www.soinside.com 2019 - 2024. All rights reserved.