关于Django新建APP

新建APP

命令

1
python manage.py startapp Name

配置文件

在setting.py中加入新增加的APP

1
2
3
4
5
6
INSTALLED_APPS = [
………………
'honor',
'aboutus',
'news',
]

修改新增APP中文件

新增template/news.html

1
2
3
4
5
6
7
8
{% extends 'base.html' %}
{% block title %}新闻资讯{% endblock %}
{% block nav_news_active %}
active
{% endblock %}
{% block content %}
<p>{{ content.content|safe }}</p>
{% endblock %}

models.py新增model

1
2
3
4
5
6
from django.db import models
from ckeditor_uploader.fields import RichTextUploadingField
# Create your models here.

class News(models.Model):
content = RichTextUploadingField()

views.py新增view

1
2
3
4
5
6
7
8
from django.shortcuts import render_to_response,get_object_or_404
from .models import News
# Create your views here.

def show_news(request):
context = {}
context['content'] = get_object_or_404(News, pk=1)
return render_to_response('news.html', context)

admin.py新增admin

1
2
3
4
5
6
7
from django.contrib import admin
from .models import News
# Register your models here.

@admin.register(News)
class NewsAdmin(admin.ModelAdmin):
list_display = ('id', 'content')

app.py新增app

1
2
3
4
from django.apps import AppConfig

class NewsConfig(AppConfig):
name = 'news'

路由文件

在项目目录下的urls.py中添加该app的路由

1
2
3
4
5
6
7
8
………………
from news.views import show_news
………………
urlpatterns = [
………………
path('news', show_news, name='news'),
………………
]

迁移数据库

还是两个步骤

1
python manage.py makemigrations
1
python manage.py migrate

使用

在base.html中就可以使用该app了

1
<li class="{% block nav_news_active %}{% endblock %}"><a href="{% url 'news' %}">新闻资讯</a></li>

:转载文章请注明出处,谢谢~