0

I have the following urls:

url(r'^(?P<college_name>\w+)/$', views.detail, name="detail"),
url(r'^(?P<photographer_username>\w+)/$', views.photographer, name="photographer"),

It works when I do /college_name url, but when typing in a photographer such as website.com/johnsmith it only searches the first url pattern and then stops.

If I put the photographer url pattern first, it works for photographers and not for colleges.

How do I fix it so it works for both?

1
  • How do you expect the computer to figure out which URL you want to access? This cannot be done. Commented Mar 11, 2017 at 23:13

3 Answers 3

2

You should differentiate the two url patterns, otherwise the later will always be shadowed by the former.

Maybe prepend a unique string to both:

url(r'^college/(?P<college_name>\w+)/$', views.detail, name="detail"),
url(r'^photographer/(?P<photographer_username>\w+)/$', views.photographer, name="photographer"),
Sign up to request clarification or add additional context in comments.

Comments

2

How could this possibly ever work? As you say, the regex is the same. So how could Django know which view you meant? It can't, so it just picks the first one.

The only way to fix this is to change your URLs so that they don't only have the name: eg "/photographer/(?P\w+)/$", etc.

Comments

1

As others have said, the computer cannot figure out which view to pick on it's own. The best solution is to have distinct paths like /photographer/ and /college/.

If you insist that both views use the same url scheme, you need to tell the program how to differentiate.

Url definition:

url(r'^(?P<photographer_or_college>\w+)/$', photographer_or_college_view, name="photographer_or_college")

View that picks one or the other:

def photographer_or_college_view(request, photographer_or_college):
    try:
        photographer = Photographer.objects.get(photographer_name=photographer_or_college)
    except Photographer.DoesNotExist:
        pass
    else:
        return photographer_view(request, photographer)

    college = get_object_or_404(College, college_name=photographer_or_college)
    return college_view(request, college)

This is not recommended since you will run into issues if there is a name conflict.

Comments

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.