Home > Enterprise >  question about django rendering , jsonresponse
question about django rendering , jsonresponse

Time:01-26

I'm working on an employee view. with this view I have 2 containers. 1 is for employe names, and the other should show the info as soon as I press a name. I'm trying to figure it out for 3 days but can't figure it out can someone please help me

index view where it will render

def index(request):
employe = Employe.objects.all()

context = {
    'employe': employe,

}

return render(request, 'managements/index.html', context)
    

the jsonresponse view is here

def employeInfo(request):
data = json.loads(request.body)
employeId = data['id_s']
action = data['action']
print(employeId)
print(action)
if action == 'get':
    check = Employe.objects.get(id=employeId)
    checkinfo, create = Employe.objects.get_or_create(object, id=employeId)
    print('check:', check, 'checkinfo', checkinfo)



return JsonResponse('context', safe=False)

the template is here, I tried few combinations nvm for that.

    <div >
     <div  >
     <div data-method="POST"   id="label1"> Medewerker info</div>
            {% csrf_token %}

            {% if action %}
            <ul>{{name.employe_info}}</ul>
            <ul>{{surname.checkinfo}}</ul>
            <ul>{{checkinfo.id}}</ul>
            <ul>{{rank.id}}</ul>
            <ul>{{employeInfo.name}}</ul>
            <ul>{{email.id}}</ul>
            <ul>{{phone.id}}</ul>
            <ul>{{name.id}}</ul>

            {% endif %}
<tr>
      <div >
          <div id="label2"> Medewerke</div>
          {% for profile in employe %}
                <button id="hehe" data-id_s={{profile.id}} data-action="get" >
                <a>{{ profile.name}}</a></button>


           {% endfor %}
      </div>

</tr>

I've been trying for 3 days and no progress. thank you in advance

CodePudding user response:

Are you trying to implement something like AJAX behaviour?

If you have a button with which you are using to send the POST, you can do the following (note you need to include jquery to as the following code uses jquery for the implementation of AJAX):

<button type="submit" id="employee-info-btn" data-url="{% url 'url_to_your_view_handling_the_post' %}" value="Submit button"></button>

And then have an onclick Javascript function to handle when you click the button:

$(document).on('click', '#employee-info-btn', function (e) {

    $.ajax({
        type: 'POST',
        url: $(this).data('url'),
        data: {
            // add any other HTML data attributes in this dictionary
            csrfmiddlewaretoken: getCookie('csrftoken'),
        },
        success: function (json_response) {
            // Successful AJAX response handling routine here
            // Show or hide any elements you want here e.g.
            var x = document.getElementById("id-of-element-you-want-to-show");
            x.style.display = "block";

            // or use the json_response here
        },
        error: function (xhr, errmsg, err) { }
    });
})

For the implementation of the getCookie() function, you can have a look at this part of the Django documentation.

I'm also not too sure how you are sending the POST, but I recommend you do it as a form with a submit button. See this part of the documentation for how to go about that.

CodePudding user response:

    var updateBtns = document.getElementsByClassName('info-employe')

    for( var i = 0; i < updateBtns.length; i  ) {
updateBtns[i].addEventListener('click', function(){
    var id_s = this.dataset.id_s
    var action = this.dataset.action
    console.log('id_s:', id_s, 'action:', action)

if (user === 'AnonymousUser'){
    console.log('User is not authenticated')
}else{
    infoUser(id_s, action)
    console.log('user is authenticated')
    }
})

}

    function infoUser(id_s, action){
   var url = '/employe_info/'

fetch(url, {
    method: 'POST',
    headers:{
        'Content-Type':'application/json',
        'X-CSRFToken': csrftoken,
    },
    body:JSON.stringify({'id_s': id_s, 'action': action})
     })
  .then((response)=>{
    return response.json()
  })
  .then((data)=>{
   console.log('data:', data)
   location.reload()
 })

}

srry forgot the js it's here

  •  Tags:  
  • Related