When the recipe system was in its infancy, python web finally took over a small hill

Dream eraser 2021-04-07 14:43:20
recipe infancy python web finally


Eraser , A funny senior Internet bug . New series , Let's go into Django The world .

Finished articles

Ten 、 Adding and displaying recipes

This blog will develop the core module of the menu system , Adding and displaying recipes .

10.1 Add recipes

stay Django For the realization of a function in , Adding must be a must , There is no way to follow-up without data .

The first step to implement this function is still to add HTML page . This page for taste , The process needs to call API Data rendering , No adjustment will be made at this stage .

{% extends "menuapp/frame.html" %} {% block title %} Menu system ---- Add recipes {%
endblock %} {% block content %}
<div class="container">
<h2 class="form-signup-heading"> Add recipes </h2>
<div class="well"></div>
<form class="form-horizontal" role="form" method="post">
{% csrf_token %}
<div class="form-group">
<label for="name" class="col-sm-2 control-label"> name :</label>
<div class="col-sm-6">
<input
type="text"
class="form-control"
id="name"
name="name"
placeholder=" Please enter the menu name "
/>
</div>
</div>
<div class="form-group">
<label for="technology_sel" class="col-sm-2 control-label"> process :</label>
<div class="col-sm-6">
<select name="technology" class="form-control" id="technology_sel">
<option> Fried </option>
<option> cook </option>
<option> bake </option>
<option> steamed </option>
</select>
</div>
</div>
<div class="form-group">
<label for="flavor_sel" class="col-sm-2 control-label"> taste :</label>
<div class="col-sm-6">
<select name="flavor" class="form-control" id="flavor_sel">
<option> Family routine </option>
<option> spicy </option>
<option> Strange smell </option>
<option> Black pepper </option>
</select>
</div>
</div>
<div class="form-group">
<label for="difficulty" class="col-sm-2 control-label"> difficulty :</label>
<div class="col-sm-6">
<select name="difficulty" class="form-control" id="difficulty">
<option value="1"> primary </option>
<option value="2"> intermediate </option>
<option value="3"> senior </option>
</select>
</div>
</div>
<div class="form-group">
<label for="production_time_sel" class="col-sm-2 control-label"
> Time :</label
>
<div class="col-sm-6">
<select
name="production_time"
class="form-control"
id="production_time_sel"
>
<option value="5">5 minute </option>
<option value="10">10 minute </option>
<option value="15">15 minute </option>
<option value="30">30 minute </option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<button type="submit" class="btn btn-lg btn-primary btn-block">
OK to add
</button>
</div>
</div>
</form>
</div>
{% endblock %}

add.html Add completed , Next, I'm going to views.py Supplement the document , Perfect the page call .

# Recipes add 
@user_passes_test(lambda u: u.is_staff)
def add_menu(request):
user = request.user
state = None
# When the user clicks the confirm add button 
if request.method == "POST":
n_menu = Menu(
name=request.POST.get("name", ""),
technology=request.POST.get("technology", ""),
flavor=request.POST.get("flavor", ""),
difficulty=request.POST.get("difficulty", ""),
production_time=request.POST.get("production_time", "")
)
n_menu.save()
state = "success"
context = {

"active_menu": 'add_menu',
"user": user,
"state": state
}
return render(request, "menuapp/add_menu.html", context)

Notice that there is a decorator at the top of the function , It is mainly used to determine whether the current login user is a super administrator , Otherwise, there is no permission to operate . Use the decorator , You need to import related functions in the header .

from .models import Menu
from django.contrib.auth.decorators import user_passes_test

here , visit http://127.0.0.1:8000/add page ,URL Will automatically jump to http://127.0.0.1:8000/login/?next=/add/ page , Notice that there's thunder here , That's the old BUG, After we've programmed the routing , No consideration of scenes with parameters , So the next change is urls.py The code is as follows , You can compare the differences in the contents of the revision by yourself .

from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="default"),
path("register/", views.register, name="register"),
path("login/", views.login, name="login"),
path("logout/", views.logout, name="logout"),
path("add/", views.add_menu, name="add_menu")
]

Now compile the code , Get the following interface , Indicates that this step has been completed .

Python Django Small stage goals -- The recipe system is a success
To write here needs to be right login Function to improve , Because this view can handle two situations , The first one is to jump to the home page after login , The second is to jump to the page before login after login . Modify the code as follows :

if user is not None:
auth.login(request, user)
# obtain next Address to , If there is, jump to next Address to 
target_url = request.GET.get("next", reverse("default"))
return HttpResponseRedirect(target_url)

Next, while registering users , Add administrator rights , This permission field is created by is_staff To control . modify register.html page , The modified code section looks like this :

<div class="form-group">
<label for="master" class="col-sm-2 control-label"> jurisdiction :</label>
<div class="col-sm-6">
<div class="checkbox">
<label>
<input type="checkbox" name="is_staff" id="master" /> Administrators
</label>
</div>
</div>
</div>

Continue to modify views.py file , Focus on the function head, write a check box data conversion dictionary , Then the data passed to the view through the foreground is transformed :

def register(request):
CHECKBOX_MAPPING = {
'on': True, 'off': False, }
if request.user.is_authenticated:
return HttpResponseRedirect(reverse("default"))
# User registration status information 
state = None
# When the user submits the registration information 
if request.method == "POST":
username = request.POST.get("username", "")
password = request.POST.get("password", "")
email = request.POST.get("email", "")
is_staff = CHECKBOX_MAPPING[request.POST.get("is_staff", "off")]
# Determine if the user name exists 
if User.objects.filter(username=username):
state = "user_exist"
else:
n_user = User.objects.create_user(username=username, password=password, email=email, is_staff=is_staff)
# Save the registration information to the database 
n_user.save()
state = "success" # Indicates successful registration 
context = {

"active_menu": 'default',
"user": None,
"state": state
}
return render(request, "menuapp/register.html", context)

When the above code runs successfully , Re pass register.html Page registration at the same time , You can check administrator identity , The data registered in the database is as follows .

Python Django Small stage goals -- The recipe system is a success
Up to now , If you sort out the whole process , After login, you can access the menu page Web Applied .
remarks , If you are not an administrator add/ Will automatically jump back to the home page .

10.2 Menu list

Give priority to the simplest list page , When reading recipe data , To prevent large amounts of data from being read at one time , So you need to use the projection method , Read some data fields .

views.py newly added menu_list function , This function requires the user to be logged in to access , At the beginning of the file, pay attention to import the corresponding function .

from django.contrib.auth.decorators import user_passes_test, login_required
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage # The paging component 
@login_required
def menu_list(request):
user = request.user
menus = Menu.objects.all()
# Data paging 
paginator = Paginator(menus, 10)
page = request.GET.get("page")
# Paging exception handling 
try:
menus = paginator.page(page)
except PageNotAnInteger:
menus = paginator.page(1)
except EmptyPage:
menus = paginator.page(paginator.num_pages)
context = {

"user": user,
"active_menu": "view_menu",
"menu_list": menus
}
return render(request, "menuapp/list.html", context)

This function realizes the basic paging function , But the classification function of recipes , Has not been implemented , It will continue to be supplemented later . Realized menu_list After the function , Right now urls.py File modification .

urlpatterns = [
path("", views.index, name="default"),
path("register/", views.register, name="register"),
path("login/", views.login, name="login"),
path("logout/", views.logout, name="logout"),
path("add/", views.add_menu, name="add_menu"),
path("list/", views.menu_list, name="menu_list")
]

The preparations have been completed , stay templates/menuapp New files in list.html, Add the following code , Part of the template language is used in this code .

{% extends "menuapp/frame.html" %} {% block title %} Menu system ---- List page {%
endblock %} {% block content %}
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="col-md-2">
<div class="list-group">
<a href="{% url 'menu_list'%}"> All the recipes </a>
<!-- Post processing into the menu classification -->
</div>
</div>
<div class="col-md-9 col-md-offset-1">
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th> Recipe name </th>
<th> process </th>
<th> taste </th>
<th> difficulty </th>
<th> Time </th>
</tr>
</thead>
<tbody>
{% for menu in menu_list %}
<tr>
<td>{
{forloop.counter}}</td>
<td>{
{ menu.name }}</td>
<td>{
{ menu.technology }}</td>
<td>{
{ menu.flavor }}</td>
<td>{
{ menu.difficulty }}</td>
<td>{
{ menu.production_time }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<nav>
<ul class="pager">
{% if menu_list.has_previous %}
<li class="previous">
<a
href="{% url 'menu_list' %}?page={
{ menu_list.previous_page_number }}"
> The previous page </a
>
</li>
{% else %}
<li class="previous disabled">
<a href="#"> The previous page </a>
</li>
{% endif %} The first {
{ menu_list.number }} / {
{
menu_list.paginator.num_pages }} page {% if menu_list.has_next %}
<li class="next">
<a
href="{% url 'menu_list' %}?page={
{ menu_list.next_page_number }}"
> The next page </a
>
</li>
{% else %}
<li class="next disabled">
<a href="#"> The next page </a>
</li>
{% endif %}
</ul>
</nav>
</div>
</div>
</div>
</div>
{% endblock %}

The final effect of the first draft is as follows , A menu system list page with pagination has been completed .

Python Django Small stage goals -- The recipe system is a success

10.3 This blog section

This blog adds to the menu system 、 List and paging functions , A mini menu management system has begun to take shape , The follow-up is to improve and modify it , I hope you can learn from this blog , thank .

Related reading

  1. Python Reptiles 100 Example tutorial , Great crawler tutorial , Subscribe now
  2. Python Game world ( Updating , Target number of articles 50+, Now subscribe to , It's all old powder )
  3. Python Reptile lesson , wonderful 9 speak

Today is the first day of continuous writing 128 / 200 God .
If you want to build a close relationship with a blogger , You can pay attention to the official account number of the same name Dream eraser , Close contact with a funny advanced Internet bug .
Blogger ID: Dream eraser , I hope you all. give the thumbs-up Comment on Collection .

django course django Chinese document Django file django What basis is needed first django project django Website building tutorial django How to use the framework django Components stay django Create project in
版权声明
本文为[Dream eraser]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/04/20210407143640899D.html

  1. 安装python
  2. 按尺寸切片pandas数据集DataFrame到多个文件
  3. Install Python
  4. Slice the pandas dataset dataframe to multiple files by size
  5. python 求最大值、最小值、平均值
  6. Finding maximum, minimum and average in Python
  7. 认识Python解释器和PyCharm编辑器
  8. Know Python interpreter and pycharm editor
  9. Python 小数据池和代码块缓存机制
  10. Python small data pool and code block caching mechanism
  11. python刷题-序列求和
  12. python刷题-圆的面积
  13. Sequence summation in Python
  14. The area of a circle
  15. Python functions, advanced syntax and usage
  16. Teach you to crawl novels in Python! Who can pay for novels these days!
  17. Python入门学习之:10分钟1500访问量
  18. Introduction to Python: 1500 visits in 10 minutes
  19. 数据分析之Pandas合并操作总结
  20. OpenCV-Python 雪花飘落特效
  21. Pandas merge operation summary of data analysis
  22. Opencv Python snowflake falling effect
  23. python logging模块“另一个程序正在使用此文件,进程无法访问。”问题解决办法
  24. Python logging module "this file is being used by another program and cannot be accessed by the process." Problem solving
  25. Mac 下python3 [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed 解决方法
  26. Python 3 [SSL: Certificate] on MAC_ VERIFY_ Failed] certificate verify failed solution
  27. Python学习之解决python下载第三方依赖速度慢的问题
  28. Python learning to solve the problem of slow download speed of third party dependence on Python
  29. python操作Excel文件报lrd.biffh.XLRDError
  30. How to operate excel file with Python lrd.biffh.XLRDError
  31. 2021的挑战与机遇,今年Python数据分析岗位会很香!
  32. The challenge and opportunity of 2021, python data analysis post will be very popular this year!
  33. 【C++简明教程】Python和C++指定元素排序比较
  34. Comparison of Python and C + + specified element sorting
  35. Python Flask使用Nginx做代理时如何获取真实IP
  36. How to get real IP address when Python flash uses nginx as proxy
  37. Python培训出来好找工作吗?好找工作的关键是什么?
  38. Is Python training easy to find a job? What is the key to finding a good job?
  39. 从零开始学python | 什么是Python JSON?
  40. Learn Python from scratch | what is Python JSON?
  41. 用 Python 读写 Excel 表格
  42. Python装饰器高级用法
  43. Reading and writing excel table with Python
  44. Python decorator advanced usage
  45. 从零开始学python | 什么是Python JSON?
  46. Learn Python from scratch | what is Python JSON?
  47. Python with关键字原理详解
  48. Python with keyword principle
  49. python + uiautomator2 实现钉钉工单提交
  50. 一个神级般的 Python 调试神器
  51. Nail work order submission based on Python + uiautomator2
  52. A magic Python debugging artifact
  53. 从零开始学python | 什么是Python JSON?
  54. Learn Python from scratch | what is Python JSON?
  55. 上手Pandas,带你玩转数据(3)-- pandas数据存入文件
  56. Start pandas, take you to play with data (3) -- save pandas data into file
  57. Python能代替shell吗?有什么特点?
  58. Can Python replace shell? What are the features?
  59. Scikit-learn 机器学习库介绍!【Python入门】
  60. Scikit learn machine learning library introduction! [introduction to Python]