Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to create a custom admin template url, getting errors Template errors & creating custom admin site errors

I am using this blog: https://medium.com/@adriennedomingus/adding-custom-views-or-templates-to-django-admin-740640cc6d42

Unable to make a custom template view in the Django Admin. I am getting django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet

If I comment out the app in the settings.py, I get error admin.site.register(Template, TemplateAdmin) NameError: name 'Template' is not defined.

If I import the Template from django.templates then I get TypeError: 'type' object is not iterable

Unable to do: 1) custom_admin_site.register & 2) models.Template is not found. Says there is no Template in models.

I have this on admin.py:

from django.contrib import admin
from django.db import models
from django.templates import Template
class TemplateAdmin(admin.ModelAdmin):
    change_form_template = ‘admin/test_attempt.html’

admin.site.register(Template, TemplateAdmin)

if I register with CustomAdminSite then I get register for model in model_or_iterable: TypeError: 'MediaDefiningClass' object is not iterable error:

CustomAdminSite.register(Template, TemplateAdmin)

# Even the following doesnot work
# custom_site_admin.register(Template, TemplateAdmin)

I have this on views.py:

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader

def preview(self, request, object_id):
    context = {}

    context = {
        **self.each_context(request),
        'title': self.index_title,
        # Unable to get this app_list as well
        # 'app_list': app_list,
    }

    request.current_app = self.name
    #load_template = request.path.split('/')[-1]
    #template = loader.get_template('admin/' + load_template)
    template = loader.get_template('admin/test_attempt.html')
    return HttpResponse(template.render(context, request))

I have this on urls.py:

from .views import preview

class CustomAdminSite(admin.AdminSite):
    def get_urls(self):
    urls = super(CustomAdminSite, self).get_urls()
    custom_urls = [
        path(r’^admin/test/(?P<object_id>\d+)$’, self.admin_view(preview), name=”preview”),
    ]
    return urls + custom_urls

I have this on my apps.py:

class CustomAdminSiteConfig(AdminConfig):
    default_site = 'batchexits.admin.CustomAdminSite'

I have added this in my settings.py registered apps:

'batchexits.admin.CustomAdminSiteConfig',

I have read this: how to fix django admin "You don't have permission to view or edit anything."?

Any help to get this working is appreciated.

like image 476
Gary Avatar asked Mar 07 '26 16:03

Gary


2 Answers

I'm not 100% sure what it is you are trying to do, but it looks like you want a custom view added on to the standard django admin for a particular model. If this is the case you can leave AdminSite alone, you probably don't need to customise that at all. I have rearranged your code a bit, into something more like what it needs to be. I have not fixed everything because I'm not sure what it is you want, so don't copy and paste this, but I'll explain the relevant bits which will hopefully get you pointed in the right direction.

You shouldn't need to add anything to your apps in settings.py. The admin django.contrib.admin and hopefully your app us already listed as well (if not you will need to first add that, and then add your models before you think about adding an admin interface for them).

class TemplateAdmin(admin.ModelAdmin):
    change_form_template = ‘admin/test_attempt.html’   # 1

    def get_urls(self):  # 2
        urls = super().get_urls()
        admin_site = self.admin_site
        custom_urls = [
            path(
                r’^(?P<object_id>\d+)/test/$’,
                self.admin_view(self.preview),        # 3
                name="preview"),              
        ]
        return urls + custom_urls

    def preview(self, request, object_id): # 4 
        context = {}

        context = {
            **self.each_context(request),
            'title': self.index_title,
            # Unable to get this app_list as well
            # 'app_list': app_list,
        }

        request.current_app = self.name
        #load_template = request.path.split('/')[-1]
        #template = loader.get_template('admin/' + load_template)
        template = loader.get_template('admin/test_attempt.html') # 4
        return HttpResponse(template.render(context, request))


admin.site.register(Template, TemplateAdmin)  # 5

# 1

This is the template that will be used when you click through to inspect or change (or add for that matter) a particular instance of a model that you have. If you are going to have a link to your new view, you will need to change this template and add a link in to whatever url you define at # 3. By the way, if all you want to do is to customise this view, you can ignore everything else, all you need to do is add what you need to that template.

# 2

You need to understand why we are having to use get_urls. Normally to return a particular view, you set something up in urls.py which will point to a particular view, that you have (normally defined somewhere like views.py). However we are wanting to add an admin view, and all of the urls starting admin/... are dealt with inside the admin app. To get around this django provides us with the get_urls method in ModelAdmin, so we can add in extra views.

# 3

self.admin_view() just adds in some additional logic about authorization, so that we don't have to worry about that. Note in the line above, we only need to add the end part of the url, so the full url will be admin/app/model//test

# 4

This is where we define your extra view, it makes sense to add the view as a method of this ModelAdmin since it relates directly to it.

# 5

In the tutorial you were following, the writer must have some model called Template (which is perhaps a pretty confusing name for a model), and you need to replace Template with whatever model you are making this view for). It also makes sense to rename TemplateAdmin to something more appropriate (if your model is called Car call it CarAdmin).

I hope this helps.

EDIT: Following the link you added in the comment below, I am guessing you are trying to achieve the tasks outlined here: https://github.com/ganeshkbhat/pr/blob/master/admintmpl/admin.py. Namely:

# TASK:
# need custom admin template inside admin that shows
#       all questions assigned to user
#       filter option sort by user

# TASK:
# Create test template which shows inside admin
#       1. question
#           - INLINE options - 2 answers (4 options max)
#       2. question
#           - INLINE options - 2 answers (4 options max)
#       Submit
# On submit save to QuestionsAnswered

These tasks can all be achieved without anything very custom at all, definitely not the kind of thing that is needed in the tutorial that you have been following. I'm not going to answer this all here, because it goes way beyond what this question is asking. But I would advise you to look at the django docs here: https://docs.djangoproject.com/en/dev/ref/contrib/admin/ They provide an exlanation as to how to do all of the things you need.

like image 107
tim-mccurrach Avatar answered Mar 09 '26 05:03

tim-mccurrach


The blog that you are referring to will be confusing to even an experienced Django developer. It has very small code snippets, so you're obviously totally confused about the missing bits of code. For example

  1. This line that you added is incorrect: from django.templates import Template # THIS IS WRONG!

Template here is the 'model' class that the blog author has created (it's also not a good name for a model – it's too generic). So basically you'll have something like this in your models.py:

from django.db import models

class Template(models.Model):
    some_model_field = models.CharField()
    ...

Then in your admin you can do from .models import Template.

  1. The section about CustomAdminSite in the blogpost isn't essential to creating custom template, and will just confuse you.

  2. In any case, you've to list the apps under INSTALLED_APPS in settings.py. You can't remove them from there.

  3. You are also confusing the nomenclature: Templates and (Django) Apps are entirely different concepts. The idea of Templates & Views is the same whether you are customizing the Django Admin or custom webpages. Django Admin is just a custom helper site that Django provides. You can definitely customize the Django Admin and don't have to create custom webpages external to the Django Admin. However you'll have have to work within the Django Admin architecture.

Here's a much better blog post that might be somewhat related to what you're doing. I would suggest you undo the things you did and start afresh.

like image 20
Nitin Nain Avatar answered Mar 09 '26 06:03

Nitin Nain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!