0

I'm trying to use url names to send a custom arg to my TemplateView.

Urls.py

urlpatterns = [
url(r'^$', index.as_view(template_name='index.html', gotodiv='whatis'), name='whatis'),
url(r'^$', index.as_view(template_name='index.html', gotodiv='whybepartofit'), name='whybepartofit')
]

Views.py

class index(TemplateView):
template_name = "index.html"
gotodiv = ''

def get_context_data(self, **kwargs):
    context = super(index, self).get_context_data(**kwargs)
    context['gotodiv'] = self.gotodiv
    return context

Template

 <li>
    <a href="{% url 'whatis' %}">What is it?</a>
 </li>
 <li>
    <a href="{% url 'whybepartofit' %}">Why be part of it?</a>
 </li>

The problem is that it doesn't care about the url name, because the patterns match in both cases. So it always goes to the first pattern (in this example, the one with the "whatis" gotodiv arg. Is there a way to configure the pattern so it only care about the name?.

Thanks

1
  • As an aside, it would be better to name your class-based-view Index. If you use lowercase index it looks like a function-based-view to other Django users. Commented Apr 23, 2018 at 12:47

1 Answer 1

1

As you have found, you can only have one URL pattern for r'^$', because Django will use the first pattern that matches.

You could change the URL to:

urlpatterns = [
    url(r'^$', index.as_view(template_name='index.html'), name='index'),
]

Then add the anchors to the links in the template:

 <li>
    <a href="{% url 'index' %}#whatis">What is it?</a>
 </li>
 <li>
    <a href="{% url 'index' %}#whybepartofit">Why be part of it?</a>
 </li>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! that was the first thing i try, but didn't work then. Gave it a second try after your answer and works perfectly!

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.