관리자에게 Django 앱에 자세한 이름을 지정할 수 있습니까?
Django 관리자에 나타나는 필드와 모델에 자세한 이름을 지정할 수있는 것과 같은 방법으로 앱에 사용자 지정 이름을 지정할 수 있습니까?
장고 1.8+
새로운 응용 프로그램은 피해야
default_app_config
합니다. 대신에 적절한AppConfig
서브 클래스에 대한 점으로 구분 된 경로를 명시 적으로 구성해야합니다INSTALLED_APPS
.
예:
INSTALLED_APPS = [
# ...snip...
'yourapp.apps.YourAppConfig',
]
그런 다음 AppConfig
아래 나열된대로 변경하십시오 .
장고 1.7
rhunwicks의 OP에 대한 언급에서 알 수 있듯이, 이것은 장고 1.7 이후 즉시 가능합니다.
문서 에서 가져온 것 :
# in yourapp/apps.py
from django.apps import AppConfig
class YourAppConfig(AppConfig):
name = 'yourapp'
verbose_name = 'Fancy Title'
그런 다음 default_app_config
변수를YourAppConfig
# in yourapp/__init__.py
default_app_config = 'yourapp.apps.YourAppConfig'
장고 1.7 이전
모델 정의에서 app_label을 정의하여 애플리케이션에 사용자 정의 이름을 지정할 수 있습니다. 그러나 django가 관리자 페이지를 작성함에 따라 app_label로 모델을 해시하므로 하나의 애플리케이션에 표시하려면 모든 애플리케이션 모델에서이 이름을 정의해야합니다.
class MyModel(models.Model):
pass
class Meta:
app_label = 'My APP name'
rhunwicks의 OP에 대한 언급에서 알 수 있듯이, 이것은 장고 1.7 이후 즉시 가능합니다.
문서 에서 가져온 것 :
# in yourapp/apps.py
from django.apps import AppConfig
class YourAppConfig(AppConfig):
name = 'yourapp'
verbose_name = 'Fancy Title'
그런 다음 default_app_config
변수를YourAppConfig
# in yourapp/__init__.py
default_app_config = 'yourapp.apps.YourAppConfig'
앱에 둘 이상의 모델이있는 경우 메타 정보가있는 모델을 만들고 모든 모델에 대해 해당 클래스의 하위 클래스를 만듭니다.
class MyAppModel(models.Model):
class Meta:
app_label = 'My App Label'
abstract = True
class Category(MyAppModel):
name = models.CharField(max_length=50)
그들에게 verbose_name 속성을 제공하십시오.
희망을 가지지 마십시오. 또한 django.contrib.admin.sites의 색인보기를 자신의 ProjectAdminSite보기로 복사하여 사용자 정의 관리 인스턴스에 포함시켜야합니다.
class ProjectAdminSite(AdminSite):
def index(self, request, extra_context=None):
copied stuff here...
admin.site = ProjectAdminSite()
then tweak the copied view so that it uses your verbose_name property as the label for the app.
I did it by adding something a bit like this to the copied view:
try:
app_name = model_admin.verbose_name
except AttributeError:
app_name = app_label
While you are tweaking the index view why not add an 'order' property too.
Well I started an app called todo and have now decided I want it to be named Tasks. The problem is that I already have data within my table so my work around was as follows. Placed into the models.py:
class Meta:
app_label = 'Tasks'
db_table = 'mytodo_todo'
Hope it helps.
For Django 1.4 (not yet released, but trunk is pretty stable), you can use the following method. It relies on the fact that AdminSite now returns a TemplateResponse, which you can alter before it is rendered.
Here, we do a small bit of monkey patching to insert our behaviour, which can be avoided if you use a custom AdminSite subclass.
from functools import wraps
def rename_app_list(func):
m = {'Sites': 'Web sites',
'Your_app_label': 'Nicer app label',
}
@wraps(func)
def _wrapper(*args, **kwargs):
response = func(*args, **kwargs)
app_list = response.context_data.get('app_list')
if app_list is not None:
for a in app_list:
name = a['name']
a['name'] = m.get(name, name)
title = response.context_data.get('title')
if title is not None:
app_label = title.split(' ')[0]
if app_label in m:
response.context_data['title'] = "%s administration" % m[app_label]
return response
return _wrapper
admin.site.__class__.index = rename_app_list(admin.site.__class__.index)
admin.site.__class__.app_index = rename_app_list(admin.site.__class__.app_index)
This fixes the index and the app_index views. It doesn't fix the bread crumbs in all other admin views.
First you need to create a apps.py
file like this on your appfolder:
# appName/apps.py
# -*- coding: utf-8 -*-
from django.apps import AppConfig
class AppNameConfig(AppConfig):
name = 'appName'
verbose_name = "app Custom Name"
To load this AppConfig subclass by default:
# appName/__init__.py
default_app_config = 'appName.apps.AppNameConfig'
Is the best way to do. tested on Django 1.7
For the person who had problems with the Spanish
This code enable the utf-8 compatibility on python2 scripts
# -*- coding: utf-8 -*-
No, but you can copy admin template and define app name there.
I'm using django-admin-tools for that.
There is a hack that can be done that does not require any migrations. Taken from Ionel's blog and credit goes to him: http://blog.ionelmc.ro/2011/06/24/custom-app-names-in-the-django-admin/
There is also a ticket for this that should be fixed in Django 1.7 https://code.djangoproject.com/ticket/3591
"""
Suppose you have a model like this:
class Stuff(models.Model):
class Meta:
verbose_name = u'The stuff'
verbose_name_plural = u'The bunch of stuff'
You have verbose_name, however you want to customise app_label too for different display in admin. Unfortunatelly having some arbitrary string (with spaces) doesn't work and it's not for display anyway.
Turns out that the admin uses app_label. title () for display so we can make a little hack: str subclass with overriden title method:
class string_with_title(str):
def __new__(cls, value, title):
instance = str.__new__(cls, value)
instance._title = title
return instance
def title(self):
return self._title
__copy__ = lambda self: self
__deepcopy__ = lambda self, memodict: self
Now we can have the model like this:
class Stuff(models.Model):
class Meta:
app_label = string_with_title("stuffapp", "The stuff box")
# 'stuffapp' is the name of the django app
verbose_name = 'The stuff'
verbose_name_plural = 'The bunch of stuff'
and the admin will show "The stuff box" as the app name.
"""
If you already have existing tables using the old app name, and you don't want to migrate them, then just set the app_label on a proxy of the original model.
class MyOldModel(models.Model):
pass
class MyNewModel(MyOldModel):
class Meta:
proxy = True
app_label = 'New APP name'
verbose_name = MyOldModel._meta.verbose_name
Then you just have to change this in your admin.py:
#admin.site.register(MyOldModel, MyOldModelAdmin)
admin.site.register(MyNewModel, MyOldModelAdmin)
Be aware that the url will be /admin/NewAPPname/mynewmodel/ so you might just want to make sure that the class name for the new model looks as close to the old model as possible.
The following plug-and-play piece of code works perfectly since Django 1.7
. All you have to do is copy the below code in the __init__.py
file of the specific app and change the VERBOSE_APP_NAME
parameter.
from os import path
from django.apps import AppConfig
VERBOSE_APP_NAME = "YOUR VERBOSE APP NAME HERE"
def get_current_app_name(file):
return path.dirname(file).replace('\\', '/').split('/')[-1]
class AppVerboseNameConfig(AppConfig):
name = get_current_app_name(__file__)
verbose_name = VERBOSE_APP_NAME
default_app_config = get_current_app_name(__file__) + '.__init__.AppVerboseNameConfig'
If you use this for multiple apps, you should factor out the get_current_app_name
function to a helper file.
'Programing' 카테고리의 다른 글
Mailto 링크는 Chrome에서 아무것도하지 않지만 Firefox에서는 작동합니까? (0) | 2020.06.23 |
---|---|
Android 프로젝트에서 사용하지 않는 문자열을 찾는 간단한 방법이 있습니까? (0) | 2020.06.23 |
두 세트의 차이 얻기 (0) | 2020.06.23 |
MySQL에서 현재 날짜와 시간을 얻는 방법? (0) | 2020.06.23 |
SQL과 응용 프로그램의 계산 수행의 장단점은 무엇입니까? (0) | 2020.06.23 |