simple_tag 定义以及使用
模板中自定义方法
1. 在 App 下创建一个名为 templatetags 的 python 包
2. 在 python 中创建 python 文件 my_tag.py
3. 在 python 文件中写固定的代码
- from django import template
- register = template.Library() # register 不能变
4. 定义函数 + 加装饰器
- 1. simple_tag
- @register.simple_tag
- def reverse_url(name, *args, **kwargs):
使用:
1. 导入 {% load 文件名 %}
2. 使用 {% 函数名 参数 1 参数 2 k1=v1 %}
- from django.http.request import QueryDict
- qd = QueryDict(mutable=True) # 可编辑的字典
- qd['next'] = next
- qd.urlencode() # urlencode url 编码
- qd._mutable =True # 改为可编辑的
- qd.copy() # 深拷贝 可编辑的字典
编辑后返回当前页案例:
标签文件代码
- from django import template
- from django.urls import reverse
- from django.http.request import QueryDict
- register = template.Library() #register 这个名字不能变
- @register.simple_tag()
- def reverse_url(request,name,*args,**kwargs):
- next = request.get_full_path()
- qd = QueryDict(mutable=True)
- qd['next'] = next
- url = reverse(name,args=args,kwargs=kwargs)
- return_url = "{}?{}".format(url,qd.urlencode())
- return return_url
后端视图代码
- def user_list(request):
- users = models.User.objects.all()
- page_obj = pagination.Pagination(request.GET.get('page'),len(users))
- return render(request,'user_list.html',
- {'users':users[page_obj.start:page_obj.end],'page_html':page_obj.page_html})
- def user_change(request,pk=None):
- print(request.META)
- obj = models.User.objects.filter(pk=pk).first()
- form_obj = UserForm(instance=obj)
- if request.method == 'POST':
- form_obj = UserForm(data=request.POST, instance=obj)
- if form_obj.is_valid():
- form_obj.save()
- next = request.GET.get('next')
- if next:
- url = next
- else:
- url = 'user_list'
- return redirect(url)
- title = "编辑用户" if pk else "新增用户"
- return render(request, 'form.html', {'form_obj': form_obj, 'title': title})
- # 模板文件
- {% extends 'layout.html' %}
- {% block content %}
- {% load my_tags %}
- <table class="table">
- <thead>
- <tr>
- <th>
用户名
- </th>
- <th>
密码
- </th>
- <th>
编辑
- </th>
- </tr>
- </thead>
- <tbody>
- {% for user in users %}
- <tr>
- <td>{{ user.name }}</td>
- <td>{{ user.password }}</td>
- <td>
- <a href="{% reverse_url request'user_edit'user.pk %}"> 编辑 </a>
- </td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- {{ page_html }}
- {% endblock %}
来源: http://www.bubuko.com/infodetail-3166832.html