31

I'm trying to make a generic table for listing django_tables objects. I've got everything working, except that the get_absolute_urls() on my User objects returns:

/users/<username>/

While I could create this URL, it doesn't match with the rest of the site layout, so I'm looking for another way to do this. Is there a way to override this value without breaking the built in authentication and other functionality?

Zoe
  • 27,060
  • 21
  • 118
  • 148
Jack M.
  • 30,350
  • 7
  • 55
  • 67

2 Answers2

49

You can do this in your settings.py file using the setting ABSOLUTE_URL_OVERRIDES

ABSOLUTE_URL_OVERRIDES = {
    'auth.user': lambda u: "/users/%s/" % u.username,
}

Here's a link to the official docs: https://docs.djangoproject.com/en/stable/ref/settings/

Zoe
  • 27,060
  • 21
  • 118
  • 148
Mark Lavin
  • 24,664
  • 5
  • 76
  • 70
0

As a side note:

Since django v1.7 the django.contrib.auth.models.AbstractUser no longer defines a get_absolute_url() method (see release notes).

So the OP's problem will not exist with django > v1.7 as you anyways need to define your custom get_absolute_url() method.

Now there are two way to do this:

  1. Define a get_absolute_url() method in your User model extension.
  2. Use the solution from Mark Lavin's answer to create (not overwrite) the User.get_absolute_url() through the ABSOLUTE_URL_OVERRIDES setting.
j-i-l
  • 10,281
  • 3
  • 53
  • 70
  • Hi. Could you elaborate a little? What do you mean by User model extension, where can I put my new user model e.g. `class UserTmp(User): def get_absolute_url(self): return f"/user/{self.id}/"` to? – 丶 Limeー来夢 丶 Mar 08 '22 at 08:07