Processing request in django inclusion template tag

I am new to Django and am trying to put the upload file form in the inclusion tag. Therefore, I can use it in different templates.

I 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 want to include this in the 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 pass from the template?

+6
source share
1 answer

You need to add takes_context=True when registering the tag in order to get django to pass the context object to the function:

 @register.inclusion_tag('upload_form.html', takes_context=True) 

By default, context will always be the first argument!

See the django documentation for inclusion tags for more details.

Note: carefully study on which pages you use this template tag, because the view may visualize additional forms / handle mail requests in a certain way, which may interfere with the logic provided by your tag (for example, a form check will be triggered if the page can be called mail request coming from another form). You could, for example. additionally check if any HTML element name is in request.POST if there are several forms on the page!

+11
source

Source: https://habr.com/ru/post/892862/


All Articles