Master/detail using the admin in django
I've googled and looked at the docs, but haven't found anything related to this scenario:
I got a master/detail model, defin开发者_StackOverflowed like so:
class Master(models.Model):
title = models.CharField(max_length=100)
def details_url(self):
return '<a href="here comes the url linking to details">Details</a>'
details_url.short_description = 'Link to details'
details_url.allow_tags = True
class Detail(models.Model):
master = models.ForeignKey(Master)
details = models.TextField()
They're exposed in the admin using admin.py. My question is this:
1) How can I make the details_url property in the Master-model so that when exposed in the admin.py a user can click it and go the listing of details and only see details related to that instance of Master-model?
2) If this can only be done using a custom view, how do I get the view to produce a page looking like the rest of the admin? I know I can use the same template code as the admin, but is there a faster way to produce for instance listings like the details in my case? Generic views/classes?
3) Adding Master to list_filter for the detailsAdmin-class is not possible due to the amount of Master-records. Or is it ...? And even if it was possible, how can I set filters from another page, like if I click a link in the change_list for Master-model going to the Details change_list, how can I set the filtering to be set to a specific instance of a Master model?
In short; all I want is the have the change_list filtered to only show details related to a specific master-record and reuse as much of the admin-code/featurebase as possible.
Prior to Django 1.2.4, you could create filtered links to models in the admin using GET query like this: http://your_site.com/admin/your_app/detail/?master__id__exact=2
.
But it was a bit of security hole, and got fixed. Now you'll get a SuspiciousOperation
exception if you try to filter your models using lookup that is not specified in list_filter
attribute.
Though there's a fix for that. This workaround implements a valid_lookups
attribute so that you can perform filtering using some lookups via URL get query, without having these lookups exposed in the admin interface.
For this to work, you'll need to override lookup_allowed()
method on your ModelAdmin. Here is the example code, check the post mentioned above for details.
class DetailAdmin(admin.ModelAdmin):
valid_lookups = ()
def lookup_allowed(self, lookup, *args, **kwargs):
if lookup.startswith(self.valid_lookups):
return True
return super(DetailAdmin, self).lookup_allowed(lookup, *args, **kwargs)
精彩评论