Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6352931
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T22:19:12+00:00 2026-05-24T22:19:12+00:00

I have used the following code in my models.py file: Create hyperlink to foreignkey

  • 0

I have used the following code in my models.py file:

Create hyperlink to foreignkey

class ModelAdminWithForeignKeyLinksMetaclass(MediaDefiningClass): 

    def __getattr__(cls, name):

        def foreign_key_link(instance, field):
            target = getattr(instance, field)
            return u'<a href="../../%s/%s/%s">%s</a>' % (
                target._meta.app_label, target._meta.module_name, target.id, unicode(target))

        if name[:8] == 'link_to_':
            method = partial(foreign_key_link, field=name[8:])
            method.__name__ = name[8:]
            method.allow_tags = True
            setattr(cls, name, method)
            return getattr(cls, name)
        raise AttributeError

In admin.py list_display I’ve added link_to to the beginning of each field I want a foreignkey link on. This works really well however when I turn debug off I get an attribute error. Any suggestions?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T22:19:13+00:00Added an answer on May 24, 2026 at 10:19 pm

    I stumbled on exactly the same problem, luckily, I’ve fixed it.

    The original solution (the one you used) comes from this question, my solution is based on it:

    class ForeignKeyLinksMetaclass(MediaDefiningClass):
    
        def __new__(cls, name, bases, attrs):
    
            new_class = super(
                ForeignKeyLinksMetaclass, cls).__new__(cls, name, bases, attrs)
    
            def foreign_key_link(instance, field):
                target = getattr(instance, field)
                return u'<a href="../../%s/%s/%d/">%s</a>' % (
                    target._meta.app_label, target._meta.module_name,
                    target.id, unicode(target)
                )
    
            for name in new_class.list_display:
                if name[:8] == 'link_to_':
                    method = partial(foreign_key_link, field=name[8:])
                    method.__name__ = name[8:]
                    method.allow_tags = True
                    setattr(new_class, name, method)
    
            return new_class
    

    Well, the only thing you need is to replace the original ModelAdminWithForeignKeyLinksMetaclass with the one above.

    However, it’s not the end. The most interesting part is why the original solution causes problems. The answer to this question lies here (line 31) and here (line 244).

    When DEBUG is on Django tries to validate all registered ModelAdmins (first link). There cls is a class SomeAdmin (i.e. an instance of its metaclass). When hasattr is called, python tries to find an attribute field in class SomeAdmin or in one of its super classes. Since it is impossible, __getattr__ of its class (i.e. SomeAdmin‘s metaclass) is called, where a new method is added to class SomeAdmin. Hence, when it comes to rendering the interface, SomeAdmin is already patched and Django is able to find the required field (second link).

    When DEBUG is False, Django skips the validation. When the interface is rendered Django tries to find a field (again, second link), but this time SomeAdmin is not patched, moreover model_admin is not class SomeAdmin, it is its instance. Thus, trying to find an attribute name in model_admin, python is unable to do this, neither it is able to find it in its class (SomeAdmin) as well as in any of its super classes, so an exception is raised.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have used following code to create a simple PDF file. It executes fine
I have the following structure: class FeatureType(models.Model): type = models.CharField(max_length=20) def __unicode__(self): return self.type
I have the following code in my models.py file and I'm wondering how it's
I have the following code: # app/models/part.rb class Part < ActiveRecord::Base has_many :lots #
i have used following code to repeat a process creation/close iteratively dim vProcessInfo as
I have used the following code in a number of applications to load .DLL
i have used the following code in .htaccess Options +FollowSymlinks RewriteEngine On RewriteBase /
I have the following code - it is used to load a drop down
I have used the code supplied in the following CodeProject article in the past
I have the following code in an Autofac Module that is used in my

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.