HackAfro HackAfro - 1 month ago 9
Python Question

Issues with URL conf in Django

So I'm working on a project that displays titles of and songs and albums released by a particular artiste from a database. I'm kinda stuck. I'm trying to create a page that displays the songs in an album when you click on the album link. When the link is clicked, I want the URL to display the name of the artiste and the title of the album but i keep getting served with the same error. It is matching the name of the album with artiste names.

How do I make the page display the songs in the album.

Money

Here's the codes for views

def home(request):
artistes = Artiste.objects.all()
return render(request, 'music/home.html', locals())


def details(request, artiste):
artistes = get_object_or_404(Artiste, name=artiste)
album = Artiste.objects.get(name=artiste).album_set.all()
single = Artiste.objects.get(name=artiste).song_set.filter(single=True)
return render(request, 'music/details.html', {'artistes': artistes, 'single': single, 'album':album})


def album_details(request,name,album):
albums = get_object_or_404(Album, title=album)
artistes = get_object_or_404(Artiste, name=name)
single = Album.objects.get(title=album).song_set.filter(single=False)
return render(request, 'music/album_detail.html', {'albums': albums, 'single': single})


url patterns

app_name = 'music'

urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^(?P<artiste>.+)/$', views.details, name='details'),
url(r'^(?P<name>.+)/(?P<album>.+)/$', views.album_details, name='album_details')
]


album details page

<body>
{% if artistes.album_set.all %}
{% for songs in album %}
<h4>Albums</h4>
<!--<img src="{{album.art}}"><br>
-->
<a href="{% url 'music:album_details' songs.artiste songs.title %}">{{songs.title}}</a>
<h5>{{songs.artiste}}</h5>
<h5>{{songs.title}}</h5>
{% endfor %}
{% else %}
<h3>No albums available</h3>
<h5>Check Out Songs </h5>
<ul>
{% for song in artistes.song_set.all %}
<li>{{song}} - mp3</li>
{% endfor %}
</ul>
{% endif %}


</body>
</html>

Answer

Your URLs are too generic. .+ matches everything, including things like "Wizked/Starboy" which you intended to be caught by the album_details URL.

You can fix this by switching the order of those URL patterns, but you should also make them less generic - eg r'^(?P<artiste>\w+) etc.