简体   繁体   中英

Django Check if Username already exists

Here's my forms.py,

class RegistrationForm(UserCreationForm):

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

    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.first_name = self.cleaned_data['first_name']
        if commit:
            user.save()
        return user

In views.py,

def register(request):
if request.method == 'POST':
    form = RegistrationForm(request.POST)
    if form.is_valid():
        form.save()
        username = request.POST.get('username')
        password = request.POST.get('password1')
        user = authenticate(username=username, password=password)
        login(request, user)
        return redirect(reverse('accounts:profile'))
else:
    form = RegistrationForm()
    return render(request, 'accounts/reg_form.html', {'form': form})

Right now if i'm using the same username it's raising an error which says "The view accounts.views.register didn't return an HttpResponse object. It returned None instead." How can I fix this issue?

Thank You :)

Django form by default does this for you.

You don't need specific for this. Beacuse, default User Model provided by django doesn't take duplicate username.

May be some indentation problem

def register(request):
     if request.method == 'POST':
          form = RegistrationForm(request.POST)
          if form.is_valid():
              form.save()
              . . . . 
     else:
         form = RegistrationForm()
     return render(request, 'accounts/reg_form.html', {'form': form})
     #^^^^^Indentation here take return statement outside else

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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