0

Below is my model

class Movie(models.Model):
    name = models.CharField(max_length=55)
    artists = models.ManyToManyField(Artist)

    def __str__(self):
        return self.name

Below is the View:

def moviesView(request):
    movies = Movie.objects.all()
    context = {
        "movies": movies
    }
    return render(request, 'movies/movies.html', context=context)

def movieView(request, name):
    print(name)
    movie = Movie.object.get(name=name)
    context = {
        "movie": movie
    }
    return render(request, 'movies/movie.html', context=context)

Below are the URLS:

urlpatterns = [
    path('movies', moviesView, name='movies'),
    re_path('movies/(\d+)', movieView, name='movie'),
    path('artists', artistView, name='artists')
]

Below is the template:

<h1>Movies</h1>
    {% for movie in movies %}
        <a href="{% url 'movie' movie.name %}">{{ movie.name }}</a>
        <h3>{{ movie.name }}</h3>
        {% for artist in movie.artists.all %}
            <ul>
                <li><a href="{{ artist.wiki }}">{{ artist.name }}</a></li>
            </ul>
        {% endfor %}
    {% endfor %}

If I click a movie avengers, it should carry to another page with movie details of avengers as mentioned in the model: I need to frame the url as: http://127.0.0.1:8000/movies/avengers

Mahesh
  • 3
  • 1

1 Answers1

0

You did not specify a parameter. But even if you did, it would not accept it, since \d+ only accepts a sequence of digits, not strings.

You can work with:

urlpatterns = [
    path('movies/', moviesView, name='movies'),
    path('movies/(?P<name>.*)/', movieView, name='movie'),
    path('artists/', artistView, name='artists')
]

but it is likely easier to work with path instead:

urlpatterns = [
    path('movies/', moviesView, name='movies'),
    re_path('movies/<str:name>/', movieView, name='movie'),
    path('artists/', artistView, name='artists')
]

It is also not a good idea to work with a name. A lot of characters will be percent encoded [wiki] resulting in ugly URLs. Django uses slugs to make visually pleasant URLs.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555