سؤال

I have two type of urls in my project:one is something like domain.com/firstname.lastname and another domain.com/user_id i like to rewrite the second url to first scheme:

domain.com/13243   ====>  domain.com/peter.norvig    ====>13243 is read from database

this is the section of my urls.py file:

url(r'^(?P<first_name>\w+).(?P<last_name>\w+)(.)?(?P<queueNumber>\d+)?/$',views.nameDetailIndex, name="FLSocial"),


url(r'^(?P<user_id>\d+)/$', views.idDetailIndex, name="IDSocial")

i want that when some one write url like domain.com/13243 and press enter, django automatically find the user_id in the db and find firstname and lastname and redirect the url to domain.com/peter.norvig i am also use neo4django db in my project

here is my views.py file:

def nameDetailIndex(request, first_name, last_name, queueNumber=None):
    try:
        user = User.objects.filter(firstName=first_name, lastName=last_name)
        if user:
            if not queueNumber:
                if len(user) > 1:
                    user = user[0]
            else:
                #start id counter from 1 not 0 because style of URL :D

                user = user[int(queueNumber)-1]
        else:
            raise Http404
        return render(request, 'social/public.html', {
            'user': user
        })
    except:
        raise Http404


def idDetailIndex(request, user_id):
    user = User.objects.get(id=user_id)
    return render(request, 'social/public.html', {
       'user': user
    })
هل كانت مفيدة؟

المحلول

One possible solution is to use Http Redirect. Here's an example:

def idDetailIndex(request, user_id):
    user = User.objects.get(id=user_id)
    return redirect('FLSocial', first_name=user.firstName, last_name=user.lastName)

نصائح أخرى

You need to return an HttpResponseRedirect, instead of rendering a template.

After you find the user:

first = user.first_name
last = user.last_name
return HttpResponseRedirect('/%s.%s/', %(first, last))
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top