简体   繁体   English

如何查看用户名是否已存在于 UserCreationField - Django

[英]How to see if username already exists in UserCreationField - Django

I am creating a simple registration field in Django for my website.我正在为我的网站在 Django 中创建一个简单的注册字段。 I want to see if a username already exists and display an error if it does.我想查看用户名是否已经存在,如果存在则显示错误。 For example, if I had an account with the username of hi , and another user tried to create an account with the username of hi , after they click on the submit button, I want to raise an error.例如,如果我有一个用户名为hi的帐户,而另一个用户尝试创建一个用户名为hi的帐户,则在他们单击提交按钮后,我想引发错误。 Right now, if I was to create an account with a username that already exists, Django will not create the account but does not display an error.现在,如果我要使用已经存在的用户名创建一个帐户,Django 将不会创建该帐户,但不会显示错误。 My code is down bellow.我的代码在下面。

Views.py视图.py

def index(request,*args, **kwargs):
  return render(request, "index.html", {} )

def register(request, ):
  form = CreateUserForm()
  if request.method == "POST":
    form = CreateUserForm(request.POST)
    if form.is_valid():
      form.save()
      username = form.cleaned_data.get('username')
      messages.success(request, f'Your account has been successfully created, {username} ')
      return redirect('login')


    

  context = {'form': form}
  return render(request, "register.html",  context )


def login(request,):
  return render(request,"login.html")

Forms.py Forms.py

class CreateUserForm(UserCreationForm):
  username = forms.CharField(required=True, max_length=30, ) 
  email = forms.EmailField(required=True)
  first_name = forms.CharField(required=True, max_length=50)
  last_name = forms.CharField(required=True, max_length=50)
  class Meta:
    model = User
    fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2',]
    

I don't know if you need this but here is my register.html:我不知道你是否需要这个,但这是我的寄存器。html:

<!--Might need to inherit from base.html-->
{% load crispy_forms_tags %}

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:400,700">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="{% static "registerstyles.css" %}">
<title>GoodDeed - Register</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> 
</head>
<body>
<div class="signup-form" style=" position:absolute; top: -1.5%; left: 38%;">
    <form action="" method="post">
        <h2 style=>Sign Up</h2>
        <p style="font-size: xx-small; color: #f2f2f2;">---</p>
        
        {% csrf_token %} 
        {{form|crispy}}
        
            <button type="submit" class="btn btn-primary btn-lg">Sign Up</button>
            <a href="/login" style="position: absolute; top: 90%; left: 50%; font-size: 16px !important;">Already a user? Sign in!</a>


            
        

        </div>
    </form>

    <!--Sidebar bellow-->
    
</body>

</html>

Thank you to everyone who helps!感谢所有提供帮助的人!

*** EDIT ***编辑

NEW FORMS.PY CODE***新 FORMS.PY 代码***

class CreateUserForm(UserCreationForm):
  username = forms.CharField(required=True, max_length=30, ) 
  email = forms.EmailField(required=True)
  first_name = forms.CharField(required=True, max_length=50)
  last_name = forms.CharField(required=True, max_length=50)

  
  class Meta:
    model = User
    fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2',]



  def clean(self):
    cleaned_data=super.clean()
    if User.objects.filter(username=cleaned_data["username"].exists():
      raise ValidationError("The username is taken, please try another one")
  

In your form implement the clean function as shown in the documentation文档所示,在您的表单中实现clean的 function

class CreateUserForm(UserCreationForm):
     .....
     def clean(self):
          cleaned_data=super().clean()
          if User.objects.filter(username=cleaned_data["username"].exists():
               raise ValidationError("The username is taken, please try another one")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM