Django新建app(完整版)

应用场景:Django2.0+python3.6

首先创建app
python manage.py startapp [appname]
接下来在项目的setting中写入appname
INSTALLED_APPS = [
...
    'appname',
...
]
在项目目录下的urls中设置
urlpatterns = [
    url(r'^admin/', admin.site.urls),
...
    url(r'^name/',include('appname.urls')),
...
]
在app目录下的views中写入
def cart(req):

    return render(req,'df_cart/cart.html')
在app目录下的urls设置
urlpatterns = [
...
    url(r'^',views.def_name),
...
]
写入models中内容时需注意
#创建含有外键列时,因版本问题要添加on_delete=models.CASCADE
#并且在关联别的app的数据库时,关联格式为appname.appdatebasename
class CartInfo(models.Model):
    user = models.ForeignKey('df_user.UserInfo',on_delete=models.CASCADE)
    goods = models.ForeignKey('df_goods.GoodsInfo',on_delete=models.CASCADE)
...
后台admin注册数据库
...
class CartInfoAdmin(admin.ModelAdmin):
    list_display = ['user','goods',...]
admin.site.register(CartInfo,CartInfoAdmin)
...
最后模型生成和迁移
python manage.py makemigrations
python manage.py migrate

你可能感兴趣的:(Django新建app(完整版))