Home > OS >  AJAX only updates a single django model instance
AJAX only updates a single django model instance

Time:10-03

I have a django project that shows a list of "issue" objects, and each issue object has a boolean field called "fixed". I want the user to be able to press a button that will change "fixed" using ajax, but the button only changes one of the issue objects rather than whatever "issue" that button belongs to, here's a gif of my problem

Here is my html:

{% for issue in projects.issues.all %}
    <article >
        <img  src="{{ issue.author.profile.image.url }}">
        <div >
            <div >
                <a >{{ issue.author }}</a>
                <small >{{ issue.date_posted|date:"F d, Y" }}</small>
            </div>
            <h2><a  href="{% url 'issue-detail' issue.id %}">{{ issue.title }}</a></h2>
            <p >{{ issue.description }}</p>
            <p>{{ issue.severity }}</p>
            {% if projects.author == user %}
              
              <span id="fixed_bool">{{ issue.fixed }}</span>
              
              {% csrf_token %}
              <button class = "btn btn-primary btn-sm" id="fix-button" value = "{{ issue.id }}">Fix</button>

            {% endif %}
        </div>
    </article>
{% endfor %}

Javascript:

$(document).on('click', '#fix-button', function (e) {
    e.preventDefault();
    $.ajax({
      type: 'POST',
      url: '{% url "fix_issue" %}',
      data: {
        issueid: $('#fix-button').val(),
        csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
        action: 'post'
      },
      success: function (json) {
        document.getElementById("fixed_bool").innerHTML = json['result']
        console.log(json)
      },
      error: function (xhr, errmsg, err) {

      }
    });
  })

my url

path('fix/', views.FixView, name='fix_issue'),

and my views

def FixView(request):
if request.POST.get('action') == 'post':
    result = ''
    id = int(request.POST.get('issueid'))
    issue = get_object_or_404(Issue, id=id)
    if issue.fixed == False:
        issue.fixed = True
        result = str(issue.fixed)
        issue.save()
    else:
        issue.fixed = False
        result = str(issue.fixed)
        issue.save()

    return JsonResponse({'result': result, })

Any help is greatly appreciated. Thank you!!

CodePudding user response:

The id attribute in HTML must be unique.

But every button has the same id: id="fix-button".

Therefore, in your JS code, this—$('#fix-button').val()—returns always the first button's value.

To fix this, either create unique ids for each button, or use classes:

<button >...</button>

And in your JS code, select the buttons by class name:

$(document).on('click', '.fix-button', function (e) {
    ...
    issueid: $(this).val(),
}
  • Related