Django 表单提交简单运用
程序员文章站
2022-03-23 12:29:18
...
在表单提交中会出现 CSRF 验证,先在 settings.py 将验证关闭。
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware', # 先关闭 CSRF 验证,提交就可以通过了
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
html文件
<form action="/add_book/" accept-charset="utf-8" method="post">
书名:<input type="text" name="booktitle"/> <Br/><br/>
出版社:<select name="publisher" id="">
{% for publisherItem in publishers %}
<option value="{{ publisherItem.name }}">{{ publisherItem.name }}</option>
{% endfor %}
</select><br/><br/>
<input type="submit" value="提交"/>
</form>
views.py文件
# 向数据库添加数据
def add_book(request):
if request.method == 'POST':
# request.POST.get(表单name属性的值) request.GET.get(url的key)
bookTitle = request.POST.get('booktitle',None) # 没有数据返回 None
publisherId = request.POST.get('publisher',None)
if bookTitle :
# 创建一条新的数据
newbook = models.Book.objects.create(title = bookTitle,publisher_id=publisherId)
newbook.save() # 把新创建的数据写入数据库中
return redirect('/book_list/')
# 获取到全部的出版社信息
publishers = models.Publisher.objects.all()
return render(request,'add_book.html',{'publishers':publishers})
# 删除一条数据库数据
def delete_book(request):
# 利用 GET 获取到指定的值
bookId = request.GET.get('id',None)
if bookId:
book_item = models.Book.objects.get(id = bookId) # 通过 GET 获取到ID值进行数据查询
book_item.delete() # 删除数据
return redirect('/book_list/')
下一篇: php怎么禁止科学计数法