在django包含模板标签中处理请求 [英] Handling request in django inclusion template tag
问题描述
我是Django的新手,正在尝试将一个上传文件格式放入包含标签中。所以我可以在各种模板中使用它。
I am new to Django and am trying to put an upload file form into an inclusion tag. So I can use it in various templates.
我创建了以下包含标签:
I have created the following inclusion tag:
#upload_files.py
@register.inclusion_tag('upload_form.html')
def upload_handler(context):
request = context['request']
view_url = reverse('upload.views.upload_handler')
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect(view_url)
upload_url, upload_data = prepare_upload(request, view_url)
form = UploadForm()
upload_model_list = UploadModel.objects.all().order_by('-pub_date')
我现在希望将其包含在一个模板中,所以在我的页面上:
I wish to now include this in a template, so on the page I have:
#mypage.html
{% extends 'base.html' %}
{% load upload_files %}
{% upload_handler %}
I get the following error:
upload_handler takes 1 arguments
我应该从模板中传递什么参数?
What argument should I be passing from the template?
推荐答案
您需要在注册标签时添加 Taking_context = True
,以获取django将上下文对象传递给函数:
You need to add takes_context=True
when registering the tag to get django pass the context object to the function:
@register.inclusion_tag('upload_form.html', takes_context=True)
每个默认值上下文
将永远是第一个参数!
Per default context
will always be the first argument then!
有关更多详细信息请参阅django关于包含标签的文档。
For further details see django's documentation on inclusion tags.
旁注:仔细决定您使用此模板标签的页面,因为视图可能会以某种方式呈现附加表单/处理帖子请求,可能会与你的标签提供的逻辑(例如如果页面可能由来自另一个表单的帖子请求调用,则表单验证将被触发)。你可以例如另外检查一下HTML元素的名称是否在 request.POST
中,如果您有一个页面上的多个表单!
A side note: Decide carefully on what pages you use this template tag on, because a view may render additional forms/handle post requests in a certain way that might collide with the logic your tag provides (eg. the form validation will be triggered if the page may be called by a post request coming from another form). You could eg. additionally check if some HTML element's name is in request.POST
if you have multiple forms on a page!
这篇关于在django包含模板标签中处理请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!