Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin : Class Media

I have a class Media as follows

class helloAdmin(admin.ModelAdmin):
    class Media:
        js = ['choice.js']
admin.site.register(hello,helloAdmin)

The staticfiles app prepends STATIC_URL to the media path. But I want MEDIA_URL to be prepended instead of STATIC_URL and STATIC_URL isn't empty. How can this be done?

like image 618
arjun Avatar asked Feb 26 '13 09:02

arjun


People also ask

How do I access my Django admin page?

To login to the site, open the /admin URL (e.g. http://127.0.0.1:8000/admin ) and enter your new superuser userid and password credentials (you'll be redirected to the login page, and then back to the /admin URL after you've entered your details).

What is form media in Django?

Rendering an attractive and easy-to-use web form requires more than just HTML - it also requires CSS stylesheets, and if you want to use fancy widgets, you may also need to include some JavaScript on each page.

What is admin in Django?

One of the most powerful parts of Django is the automatic admin interface. It reads metadata from your models to provide a quick, model-centric interface where trusted users can manage content on your site. The admin's recommended use is limited to an organization's internal management tool.

Where is Django admin template?

The default templates used by the Django admin are located under the /django/contrib/admin/templates/ directory of your Django installation inside your operating system's or virtual env Python environment (e.g. <virtual_env_directory>/lib/python3. 5/site-packages/django/contrib/admin/templates/ ).


1 Answers

You can achieve that with the following settings:

import os
CURRENT_PATH = os.path.abspath((os.path.dirname(__file__)))

MEDIA_ROOT = os.path.join(CURRENT_PATH, 'uploads')

MEDIA_URL = '/site_media/'

urls.py

from django.conf import settings
urlpatterns += patterns('',
    url(r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)

admin.py

class helloAdmin(admin.ModelAdmin):
    class Media:
        js = ['/site_media/choice.js']
admin.site.register(hello,helloAdmin)

Using MEDIA_URL is not advised for serving static files. According to django documentation, MEDIA_URL will not be referred for media files, when STATIC_URL is not empty. Refer to this part of documentation.

So I recommend you to use the following settings:

STATIC_ROOT = 'static/'

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(CURRENT_PATH, 'media'),
)

admin.py

class helloAdmin(admin.ModelAdmin):
    class Media:
        js = ['choice.js']
admin.site.register(hello,helloAdmin)
like image 51
arulmr Avatar answered Oct 03 '22 06:10

arulmr