Shivam Kumar Dodval Shivam Kumar Dodval - 3 years ago 248
Python Question

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 :)

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download