0

I'm trying to sort the problem of determining if a URL is available to be used as a first-level url path for objects. For example: www.myapp.com/username_1 would be available if no username_1 has previously existed.

One solution I found is this but the solution is not correct. The validation part:

def clean_username(self):
        username = super(NewRegistrationForm, self).clean_username()
        try:    resolve(urlparse('/' + username + '/')[2])
        except Resolver404, e:
            return username

        raise ValidationError(_(u'This username does not create '
                                u'a valid URL.  Please choose '
                                u'another'))

would always raise an error. It seams that there needs to be a way to check if a URL returns a 404 or not. I could use urllib however I was wondering if there was a better solution to this problem?

Many thanks.

3
  • Are you just trying to make sure that the username enters will be valid when used in a url? What is the regex of the url? Why can't u just match it against that? Commented Oct 2, 2013 at 2:10
  • Just create a normal url and let the view return a 404 if the user doesn't exist? Commented Oct 2, 2013 at 6:03
  • @Wolph I'm exactly doing that. The problem is figuring out if the URL is returning a 404 when a user signs up with a particular username. The url pattern I'm matching agains is: url(r'^(?P<username>[-\w]+)/$', profile_view, {}, 'profile') Commented Oct 2, 2013 at 7:29

1 Answer 1

1

There is no need to involve urls in this case (if I understand what you are doing correctly).

Just use something like this instead (assuming Django 1.5 or higher):

from django.contrib import auth

def clean_username(username):
    url = urlresolvers.reverse('your_view_name', kwargs=dict(username=username))
    match = urlresolvers.resolve(url)
    if match.view_name != 'your_view_name':
        raise ValidationError(_(
            u'This username does not create a valid URL.  Please choose another'))

    if auth.get_user_model().objects.filter(username__iexact=username):
        raise ValidationError(_(u'There is already a user with this username'))

    return username
Sign up to request clarification or add additional context in comments.

3 Comments

The problem is that I don't want people using usernames that resolve to other urls e.g. /admin, /settings etc. See elfsternberg.com/2009/06/26/…
@ip.: try the new version :)
Yep that's awesome! Thanks! Another question I could use some help with is stackoverflow.com/questions/19128171/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.