学习笔记,仅供参考,有错必纠

参考自:Django打造大型企业官网–Huang Y;



文章目录



QueryDict对象



我们平时用的​​request.GET​​​和​​request.POST​​​都是​​QueryDict​​​对象,这个对象继承自​​dict​​​,因此,用法跟​​dict​​​相差无几,其中用得比较多的是​​get​​​方法和​​getlist​​方法。



  • 举个例子


我们定义一个添加图书的模板文件add_book.html:

{% extends "basePage.html" %}

{% block content %}

<h2>添加图书</h2>

<form method="POST" action="">
{% csrf_token %}
<table>
<tr>
<td>图书名:</td>
<td><input type="text" name="book"></td>
</tr>
<tr>
<td>价格:</td>
<td><input type="text" name="price"></td>
</tr>

<tr>
<td>标签:</td>
<td>
<label>
python
<input type="checkbox" name="tags" value="python">
</label>
<label>
Java
<input type="checkbox" name="tags" value="Java">
</label>
<label>
Matlab
<input type="checkbox" name="tags" value="Matlab">
</label>
<label>
R
<input type="checkbox" name="tags" value="R">
</label>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="添加"></td>
</tr>
</table>
</form>

{% endblock %}



主urls.py文件:

from django.contrib import admin
from django.urls import path
from . import views
from django.conf.urls import include

urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name = "index"),
path("redirect/", views.redir, name = "redir"),
path("front/", include("front.urls")),
path("add_book/", views.add_book, name = "add_book"),

]

主views.py文件:

@require_http_methods(['GET', 'POST'])
def add_book(request):
if request.method == "GET":
return render(request, "add_book.html")
else:
book = request.POST.get("book", "None")
price = request.POST.get("price", "0")
tags = request.POST.getlist("tags")

context = {
"book":book,
"price":price,
"tags":tags
}
return render(request, "show_books.html", context = context)

定义显示图书的模板show_books.html:

{% extends "basePage.html" %}

{% block content %}

<h2>显示图书</h2>

<table>
<tr>
<td>图书名:</td>
<td>{{ book }}</td>
</tr>
<tr>
<td>价格:</td>
<td>{{ price }}</td>
</tr>

<tr>
<td>标签:</td>
<td>{{ tags }}</td>
</tr>

</table>
{% endblock %}



向http://127.0.0.1:8000/add_book/发起请求:

Django从理论到实战(part42)--QueryDict对象_django

点击​​提交​​:

Django从理论到实战(part42)--QueryDict对象_django_02