[英]How to add a Model (not an app) to django?
I am using django 1.3 and just trying to add a simple model(not an app) to the admin site. 我正在使用django 1.3,只是尝试将一个简单的模型(不是应用程序)添加到管理站点。 so i have tried:
所以我试过了:
from django.db import models
class UserProfile(models.Model):
notes = models.TextField(db_name="Notes", max_length=15)
def _str_(self):
return self.notes
class Admin:
pass
and have also tried creating the admin.py file in the site root and in the /static/admin/ directory and have attempted two standard entries for it as follows: 并且还尝试在站点根目录和/ static / admin /目录中创建admin.py文件,并尝试了两个标准条目,如下所示:
from django.contrib import admin
from mock.models import UserProfile
admin.site.register(UserProfile)
and 和
from django.contrib import admin
from mock.models import UserProfile
class UserProfileAdmin(admin.ModelAdmin):
pass
admin.site.register(UserProfile, UserProfileAdmin)
any help would be much appreciated. 任何帮助将非常感激。 Thank you very much.
非常感谢你。
Don't define your Admin
class in the model itself like below. 不要在模型本身中定义您的
Admin
类,如下所示。 That's the really old way to do it, from before Django 1.0. 从Django 1.0开始,这是真正做旧的方法。 I'm not sure what tutorial or documentation you are using, but it's very out of date.
我不确定您使用的教程或文档,但它已经过时了。
class UserProfile(models.Model):
notes = models.TextField(db_name="Notes", max_length=15)
# don't do this!
class Admin:
pass
Defining a UserProfileAdmin
is the correct approach. 定义
UserProfileAdmin
是正确的方法。 The admin.py file should not go in the /static/admin/
. admin.py文件不应该放在
/static/admin/
。 The static directory is for static files like CSS stylesheets and javascript files, not for Django code. 静态目录用于静态文件,如CSS样式表和javascript文件,不适用于Django代码。
As for your question of whether you can define a model without defining an app, it's not a really good idea. 至于你是否可以在没有定义应用程序的情况下定义模型的问题,这不是一个好主意。 Lots of parts of django assume that each model belongs to an app.
django的很多部分假设每个模型都属于一个应用程序。 For example the database table name is
appname_modelname
. 例如,数据库表名是
appname_modelname
。
Creating an app doesn't take too long. 创建应用程序不会花太长时间。 Run the startapp command and it will create the base directory and files.
运行startapp命令,它将创建基本目录和文件。
./manage.py startapp <appname>
All you then need to do is add the new app to INSTALLED_APPS
, and create your admin.py
file. 您需要做的就是将新应用程序添加到
INSTALLED_APPS
,并创建您的admin.py
文件。
As your project gets bigger, keeping models in apps will keep it more organized. 随着项目变得越来越大,在应用程序中保留模型将使其更有条理。 Many Django users create an app named
utils
(or similar) for the odd model. 许多Django用户为奇数模型创建了一个名为
utils
(或类似)的应用程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.