Ask Your Question
3

What is the process of generating clickable links for foreign keys in the Django admin panel?

asked 2023-05-24 19:09:11 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-24 19:25:02 +0000

david gravatar image

The process for generating clickable links for foreign keys in the Django admin panel involves the following steps:

  1. In the model that has the foreign key relationship, define the related model using the ForeignKey field.

  2. In the related model, define a str method that returns a string value that will be displayed as the clickable link in the admin panel.

  3. Register both models in the admin.py file, and define a list_display attribute for the model that has the foreign key relationship.

  4. Include the related model's str method in the list_display attribute for the model that has the foreign key relationship, and enclose it in a lambda function.

Here is an example:

# models.py
class Author(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

# admin.py
class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'author_name')

    def author_name(self, obj):
        return obj.author.name
    author_name.admin_order_field = 'author__name'
    author_name.short_description = 'Author'

admin.site.register(Author)
admin.site.register(Book, BookAdmin)

In this example, the Author model is related to the Book model through a foreign key field. We define a __str__ method for both models, and include the Author model's name attribute as a display value for the clickable link.

In the BookAdmin class, we define a list_display attribute that includes a lambda function for the author_name attribute. The lambda function returns the Author model's name attribute, which will be used as the display value for the clickable link in the admin panel.

Finally, we register both models in the admin.py file, and specify the BookAdmin class as the admin class for the Book model.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-24 19:09:11 +0000

Seen: 2 times

Last updated: May 24 '23