Django passing in isbn10 to url

Viewed 47

I seem to be unable to pass in isbn10 numbers in to the Django.

    <a href="{% url 'books-to-detail' fic.isbn %}">
      <section class="slideshow-fiction">
        <img src="{{ fic.image }}" alt="" />
        <p>{{ fic.title|truncatewords:4 }}</p>
        <!-- <p>{{ fic.description }}</p> -->
        <p>{{ fic.author }}</p>
        <!-- <p>{{ fic.isbn }}</p> -->
      </section>
    </a>

Examples of the numbers are 059318808X and 0316539562. I've tried to use re_path and regex however if i get one number to pass the other does not. This is one of the paths that I've tried but 0316539562 does not pass.

re_path(
        r"^redirect/books/(?P<isbn>[0-9]*[-| ][0-9]*[-| ][0-9]*[-| ][0-9]*[-| ][0-9]*\w)/$",
        redirect_books_to_detail,
        name="books-to-detail",
    ),

The error here

Trying this url path

re_path(
        r"^redirect/books/(?P<isbn>[\w\+%_& ]+)/$",
        redirect_books_to_detail,
        name="books-to-detail",
    ),

I now get an error that there is seen here

1 Answers

The regular expression part you're using to identify ISBN numbers looks a little too complex.

ISBN10 is made of 10 characters. 9 of them should be digits, and the last one can either be a digit or the X character. Regular expressions that represent this would be something like \d{9}[\dX] or [0-9]{9}[0-9X]

You can quickly test if this matches using the python interpreter:

>>> import re

>>> re.fullmatch(r"\d{9}[\dX]", "059318808X")  # returns a match
<_sre.SRE_Match object; span=(0, 10), match='059318808X'>

>>> re.fullmatch(r"\d{9}[\dX]", "123X")        # does not return a match

>>> re.fullmatch(r"\d{9}[\dX]", "0316539562")  # returns a match
<_sre.SRE_Match object; span=(0, 10), match='0316539562'>

>>> re.fullmatch(r"\d{9}[\dX]", "03165395629999")  # does not return a match

So the path you're passing to re_path should be something like r"^redirect/books/(?P<isbn>\d{9}[\dX])/$"

If you decide to accept ISBNs containing dashes, you'd need to change the regular expression to something like (\d-?){9}[\dX] which means we're expecting 9 digits, any of them possibly (but not obligatory) followed by a dash, and then a last digit-or-X.

Related