视图
BugCalendar/hunter/views.py
from . import models
from django.http import HttpResponseRedirect
from django.shortcuts import render
# 增加白帽子信息
def add_hunter(request):
try:
hunter = models.UserInfo(nick=request.POST['nick'], email=request.POST['email'])
hunter.save()
return HttpResponseRedirect(reverse('show_hunter'))
except:
template_name = 'hunter/add_hunter'
return render(request, template_name)
# 删除白帽子信息
def delete_hunter(request, hunter_id):
hunter = models.UserInfo(id=hunter_id)
hunter.delete()
return HttpResponseRedirect(reverse('show_hunter'))
# 修改白帽子信息
def update_hunter(request, hunter_id):
hunter = models.UserInfo.objects.get(id=hunter_id)
try:
hunter.nick = request.POST['nick']
hunter.email = request.POST['email']
hunter.save()
return HttpResponseRedirect(reverse('show_hunter'))
except:
template_name = 'hunter/modify_hunter'
context = {'hunter', hunter}
return render(reqeust, template_name, context)
# 查看所有白帽子信息
def show_hunter(request):
all_hunter = models.UserInfo.objects.all()
context = {'all_hunter':all_hunter}
template_name = 'hunter/show_hunter'
return render(request, template_name, context)
模板
增加白帽子
BugCalendar/hunter/templates/hunter/add_hunter.html
<form action="{% url 'add_hunter' %}" method="POST">
<input type="text" name="nick"> <br/>
<input type="text" name="email"> <br/>
<input type="submit">
</form>
删除白帽子
#修改白帽子
BugCalendar/hunter/templates/hunter/modify_hunter.html
<form action="{%url 'update_hunter' hunter.id %}" method="POST">
<input type="text", name="nick" value="{{ hunter.nick }}"> <br/>
<input type="text", name="email" value="{{ hunter.email }}"> <br/>
<input type="submit">
</form>
查看白帽子
BugCalendar/hunter/templates/hunter/show_hunter.html
<table>
<tr>
<th>昵称</th>
<th>邮箱</th>
<th>操作</th>
</tr>
{% for hunter in all_hunter %}
<tr>
<td>{{ hunter.nick }}</td>
<td>{{ hunter.email }}</td>
<td>
<a href="{% url 'modify_hunter' hunter.id %}">修改</a> |
<a href="{% url 'delete_hunter' hunter.id %}">删除</a>
</td>
</tr>
{% endfor %}
</table>
路由
BugCalendar/hunter/urls.py
urlpattern = [
path('add_hunter/', views.add_hunter, name='add_hunter'),
path('delete_hunter/', views.delete_hunter, name='delete_hunter'),
path('modify_hunter/', views.modify_hunter, name='modify_hunter'),
path('show_hunter/', views.show_hunter, name='show_hunter'),
]