The process for generating clickable links for foreign keys in the Django admin panel involves the following steps:
In the model that has the foreign key relationship, define the related model using the ForeignKey field.
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.
Register both models in the admin.py file, and define a list_display attribute for the model that has the foreign key relationship.
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.
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
Asked: 2023-05-24 19:09:11 +0000
Seen: 2 times
Last updated: May 24 '23
How can I deal with Expression.Error related to a column in Power Query?
How can you implement pagination in Oracle for the LISTAGG() function?
What is the process for implementing a FutureBuilder on an OnTap function in Flutter?
How can we require users to be logged in before they can access the root folders in WordPress?
In SCSS, what is the method for grouping and reusing a set of classes and styles?
How can popen() be used to direct streaming data to TAR?
How does iOS retrieve information from a BLE device?
How can Django Admin accommodate a variety of formats and locales for its input fields?