django admin, at particular url, show queryset with each link to a object

I have 2 models, Question model is associated with Group model using Foreign key.

class Question(models.Model):
    comment = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    group = models.ForeignKey(
        'Group', on_delete=models.CASCADE, related_name='questions')
    question = models.FileField(
        upload_to=user_directory_path, blank=True, null=True)

    def __str__(self):
        return self.comment

class Group(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)

Now, inside admin, at some url- for example- http://127.0.0.1:8000/admin/questions/<group-id> I want to show all questions related to a group of particular ID and clicking on each question, open a particular question (like a normal model object is open).

Note- I want to use Django template.

What I found on googling(but I have tried, I didn’t reach to a solution with it)- [get_urls] (https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_urls)

Following, I am using a temporary solution (but the problem with it, is the url admin/question/question/?group__id__exact=3) basically, I am feeding a url to group name, and clicking on it ultimarlty load different result filtering as required. image

class GroupAdmin(admin.ModelAdmin):
    class Meta:
        model = Group

    list_display = ['group_wise_questions']

    def group_wise_questions(self, obj):
        redirect_url = reverse('admin:question_question_changelist')
        redirect_url1 = reverse('admin:{}_{}_changelist'.format(
            obj._meta.app_label, obj._meta.model_name)
        )
        extra = "?group__id__exact=%d" % (obj.id)
        return format_html(
            "<a href='%s'>All Questions from group (%s)</a>" % (
                (redirect_url + extra), obj.id)
        )

But I want something like http://127.0.0.1:8000/admin/questions/<group-id>.

Any help/guidance will be helpful. Thanks in advance.

This format URL means that your app name is question and the model name is question. That’s how the admin works.

If you must absolutely use a different set of URLs, I can see a couple of different options:

  1. You create a redirect function that is called when your chosen URL is supplied and redirects to the real URL.
  2. You create a view for your URLs that do the same thing as the admin page does for its url.

But, to get to what might be the more fundamental issue, is to explore why you think this might be desirable to do. If you’re looking to do this because you’re going to expose these URLs to the “outside” - whatever that may mean in your situation - then you really shouldn’t be using the admin facility for this at all.

Read the first two paragraphs from the Django documentation about the admin site.

Ken

1 Like