简体   繁体   中英

Dynamic names as first-level URL path objects in Django

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.

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

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