django-添加文章&admin后台管理

通过表单形式与后端交互:

前端表单:

add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加文章</title>
</head>
<body>

<form action="/add/" method="post" enctype="multipart/form-data">#上传图片时,一定要加上enctype属性
    <p>title :<input name="title"></p>
    </p>content :<input name="content"></p>
    </p><select name="nav_id">
        {% for nav in replace %}
        <option  value="{{ nav.id }}">{{ nav.name }}</option>
        {% endfor %}
    </select></p>
    </p><input type="file" name="img"></p>
    </p><input type="submit" value="提交"></p>
</form>

</body>
</html>

注意:

settings.py

MIDDLEWARE = [
    ‘django.middleware.security.SecurityMiddleware‘,
    ‘django.contrib.sessions.middleware.SessionMiddleware‘,
    ‘django.middleware.common.CommonMiddleware‘,
    # ‘django.middleware.csrf.CsrfViewMiddleware‘, #是防止重复提交,若访问报403禁止访问,注释掉这行数据;或者在add文件中加上{%csrf_token%}
    ‘django.contrib.auth.middleware.AuthenticationMiddleware‘,
    ‘django.contrib.messages.middleware.MessageMiddleware‘,
    ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘,
]

后端:

views.py

def add_article(request):
    #若方法是get,则返回添加页
    if request.method == ‘GET‘:
        return render(request,‘add.html‘)
    #若方式是post,则获取数据,放到数据库
    else:
        title = request.POST.get(‘title‘)
        content = request.POST.get(‘content‘)
        nav_id = request.POST.get(‘nav_id‘)
        img = request.FILES.get(‘img‘)
        models.Article.objects.create(title=title,content=content,
                                      nav_id=nav_id,img=img)#把数据存到数据库
        return HttpResponseRedirect(‘/index‘)#提交后,页面跳转重定向

urls.py

urlpatterns = [
    path(‘admin/‘, admin.site.urls),
    path(‘index/‘, views.index),
    path(‘info/<int:id>‘, views.info),
    path(‘nav/<int:id>‘, views.nav_article),
    path(‘add/‘, views.add_article)
]

 admin后台管理

1、添加管理员账号:python manage.py createsuperuser (命令),也可在pycharm中快捷操作

2、

相关推荐