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.

Community
  • 1
  • 1
ip.
  • 3,126
  • 5
  • 29
  • 41
  • 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? – jproffitt Oct 02 '13 at 02:10
  • Just create a normal url and let the view return a 404 if the user doesn't exist? – Wolph Oct 02 '13 at 06: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[-\w]+)/$', profile_view, {}, 'profile') – ip. Oct 02 '13 at 07:29

1 Answers1

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
Wolph
  • 69,888
  • 9
  • 125
  • 143
  • The problem is that I don't want people using usernames that resolve to other urls e.g. /admin, /settings etc. See http://www.elfsternberg.com/2009/06/26/dynamic-names-as-first-level-url-path-objects-in-django/ – ip. Oct 02 '13 at 11:54
  • @ip.: try the new version :) – Wolph Oct 02 '13 at 12:08
  • Yep that's awesome! Thanks! Another question I could use some help with is http://stackoverflow.com/questions/19128171/querying-for-followers-in-news-feed-based-data-model-in-django – ip. Oct 02 '13 at 12:49