[Django]-What is the difference between <int:pk> and <pk>?

6๐Ÿ‘

โœ…

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.

Leave a comment