24👍
You can use exists
:
from django.contrib.auth.models import User
if User.objects.filter(username=self.cleaned_data['username']).exists():
# Username exists
...
6👍
You can check if the username
exists with the clean_username
method and raise ValidationError:
def clean_username(self, username):
user_model = get_user_model() # your way of getting the User
try:
user_model.objects.get(username__iexact=username)
except user_model.DoesNotExist:
return username
raise forms.ValidationError(_("This username has already existed."))
If this case, you can show the error in the signup form and do not need to redirect to another page.
update:
As per @Spacedman pointed out a valid point regarding to race conditions on checking username uniqueness on Form logic against DB level’s, although your chance of getting this is very unlikely, in case you do here are the relevant SO answers that may worth reading:
How to avoid race condition with unique checks in Django
Another update
As per OP’s comment, here’s another change can be made for the views:
def register_user(request):
# be DRY, the form can be reused for both POST and GET
form = MyRegistrationForm(request.POST or None)
# check both request is a POST and the form is valid
# as you don't need to redirect for form errors, remove else block
# otherwise it's going to redirect even form validation fails
if request.method == 'POST' and form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
# I use render so need not update the RequestContext, Django does it for you
html = render(request, 'register.html', {'form': form})
return HttpResponse(html)
Hope this helps.
- "no such table" error on Heroku after django syncdb passed
- Django – Multiple apps on one webpage?
- Django: "order" a queryset based on a boolean field
- Hosting my Django site
2👍
if you are using django’s built in Usercreationform
then simply type in your template:
{{form.errors}}
This will check almost everything like:
- whether user is created or not
- passwords are matching or not
- Encoding gives "'ascii' codec can't encode character … ordinal not in range(128)"
- Django: How to save original filename in FileField?
- "no such table" error on Heroku after django syncdb passed
0👍
You can use unique=True
in models.py
username = models.CharField(max_length=30, blank=True, null=True, unique=True)
- How to make Django Password Reset Email Beautiful HTML?
- Pidbox received method enable_events() [reply_to:None ticket:None] in Django-Celery
- How to get foreignkey field name instead of id in django rest framework
- There is no South database module 'south.db.postgresql_psycopg2' for your database django