好吧,我正在创建一个基于django的网站,并且两个用户的用户名不能相同。我想在注册过程中检查用户名是否已经存在,然后在注册页面中返回一条消息以提醒该人
views.py
from .forms import UserRegisterForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
email = form.cleaned_data.get('email')
emails = User.objects.filter(is_active=True).values_list('email', flat=True)
username = form.cleaned_data.get('username')
names = User.objects.filter(is_active=True).values_list('username', flat=True)
if username in names:
messages.error(request, 'Sorry. This username is taken', extra_tags='name')
return redirect('register')
else:
user.save()
messages.success(request, "New account created")
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'user/register.html', {'form': form})
register.html
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
{{message}}
</div>
{% endfor %} ```
Some help would be nice
答案 0 :(得分:0)
您只需要检查输入的用户名是否存在于数据库中。您可以使用exists()
方法进行检查。
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
email = form.cleaned_data.get('email')
emails = User.objects.filter(is_active=True).values_list('email', flat=True)
username = form.cleaned_data.get('username')
if User.objects.filter(username=username).exists():
messages.error(request, 'Sorry. This username is taken', extra_tags='name')
return redirect('register')
else:
user.save()
messages.success(request, "New account created")
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'user/register.html', {'form': form})
因为您提到了
,所以您无需使用用户名检查来检查is_active=True
两个用户不能使用相同的用户名
答案 1 :(得分:0)
使用干净方法ref在表单中添加您的验证。