问题
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?
回答1:
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!
For further details see django's documentation on inclusion tags.
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!
来源:https://stackoverflow.com/questions/6713022/handling-request-in-django-inclusion-template-tag