2

I have field in view: <h1>{{article.author}}</h1>

And I want pass author to UR:

 <p><a href="{% url 'subscribe' user=article.author %}">Подписаться на пользователя {{article.author}}</a> </p>

URL:

  path('<user:user>',views.sunscribe, name="subscribe")

But I have error:

"URL route '%s' uses invalid converter %s." % (original_route, e) django.core.exceptions.ImproperlyConfigured: URL route '' uses invalid converter 'user'.

1

1 Answer 1

2

In short: you can not pass a User object as parameter, you can pass an encoding of (a reference to) a User, but this is typically a security risk, and will probably not make life easier than just passing the id.

It is possible that the path converters [Django-doc] give a false impression, but you can not simply parse all sorts of objects. By default (on the moment of writing), there are only five path converters: str, int, slug, uuid and path.

So you will have to find an "encoding" to pass a reference to the object. The most straightforward way is probably the primary key, so you can implement it like:

path('<int:user_id>',views.sunscribe, name="subscribe")

and in the template use it like:

<p>
  <a href="{% url 'subscribe' user=article.author.id %}">
    Подписаться на пользователя {{article.author}}
  </a>
</p>

In that case you thus obtain the id of the user, and you will need to fetch the user object.

The documentation also mentions how you can write path conversions yourself [Django-doc]. But still you will pass a representation of the object (you could, as really bad solution generate for example a pickle stream, but that would be very unsafe, since it would probably impose a severe security risk).

An URL can only contain text, not objects. So even if you write a custom path conversion, you still will need some sort of encoding and decoding.

You can of course ease the process a bit, by making a path converter, that makes the process of generating an id and retrieving the id transparent, by writing a custom path converter, like:

from django.urls.converters import IntConverter

class UserConverter:

    def to_python(self, value):
        return User.object.get(pk=value)

    def to_url(self, value):
        return value.pk

register_converter(converters.UserConverter, 'user')

This will then make the process more transparent, then you can use indeed {% url 'subscribe' user=article.author %}, and <user:user> in the path(..) definition. But I do not know if this improves the situation a lot.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.