Home > Enterprise >  Failed to get value from html page in Django
Failed to get value from html page in Django

Time:04-22

I have a problem with trying to get a response from my HTML page using Django (admin). I have a pretty simple div = contenteditable and need to pass data from this div back after the submit button was clicked.

Everything, including choosing selection and opening the intermediate page works fine. But when I tapped submit button, the condition if "apply" in request.POST failed to work.

Please, tell me, what I'm doing wrong?

This is my Django admin:

class QuestionAdmin(AnnotatesDisplayAdminMixin, admin.ModelAdmin):

def matched_skills(self, question):
    return ', '.join(s.name for s in question.skills.all())

def update_skills(self, request, queryset):
    if 'apply' in request.POST:
        print("something")
        
    skills = []
    for question in queryset:
        skills.append(self.matched_skills(question))
    return render(request,
                  'admin/order_intermediate.html',
                  context={'skills': skills})

update_skills.short_description = "Update skills"

This is my order_intermediate.html page:

{% extends "admin/base_site.html" %}
{% block content %}
<form method="post">
    {% csrf_token %}

  <h1>Adjust skills. </h1>
  {% for skill in skills %}
    <div>
    <div id="title" style="margin-left: 5px" contenteditable="true" > {{ skill }} </div>
    </div>
  {% endfor %}

  <input type="hidden" name="action" value="update_status" />
  <input type="submit" name="apply" value="Update skills"/>
</form>
{% endblock %}

CodePudding user response:

Actually, request.POST is an HttpRequest object. For getting available keys in the body of the request, you need to use "request.POST.keys()" method. So, you can simply change your condition to:

if 'apply' in request.POST.keys():
    print("something")

CodePudding user response:

In my knowledge, you can not send div content with form submit. However you can use input tag with array in name attribute for this. This will send an array as post variable when submit

First, send skills as a enumerate object from your views

return render(request, 'admin/order_intermediate.html', context={'skills': enumerate(skills)})

Then edit your html to this (Note: if you have css in title id, change it to title class)

{% for i,skill in skills %}
    <div>
        <input  name="skill[{{ i }}]" value="{{ skill }}" style="margin-left: 5px">
    </div>
{% endfor %}

and handle array with any action you want to perform in update_skills()

for skill in request.POST.getlist('skill[]'):
    # your code
  • Related