What is the difference between <int:pk> and <pk>?

Viewed 6862

Say that we are implementing a simple blog with django and that the blog posts are accessible with URLs like /posts/1/, /posts/2/ etc.

When we define the path variables in the urlpatterns array, what is the main difference between using
path('post/<int:pk>/', ..., ...) and path('post/<pk>/', ..., ...)?

Is it just good practice? Are there actual benefits?

1 Answers

Is it just good practice? Are there actual benefits?

Yes. It makes the path more specific, and allows to write other paths that do not have overlapping patterns.

The int: part is a path converter [Django-doc]. If you do not specify a path converter the str path converter will be used.

It specifies the regex that will be used. For example the IntConverter [GitHub] has as regex:

class IntConverter:
    regex = '[0-9]+'

    def to_python(self, value):
        return int(value)

    def to_url(self, value):
        return str(value)

whereas the StringConverter [GitHub] uses:

class StringConverter:
    regex = '[^/]+'

    def to_python(self, value):
        return value

    def to_url(self, value):
        return value

These are thus regexes that replace the <int:pk> or <str:pk> in a path. If you thus simply write <pk>, then it will also fire for post/foobar. You do not per se want this. For example if you later have another path:

    path('post/<int:pk>/', some_view),
    path('post/new/', other_view),

If you would write <pk> then the post/new path would also fire the some_view view, and not the other_view, since the str: path converter also matches with new.

Related