Django how to use a HTML tag attribute in views.py?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I'm trying to create a view that change a boolean and switch images from it, I already done it but I need to iterate between 12 values (asiento) and i only can point to one of them this is my Django code.



models.py:



class Asientos(models.Model):
asiento = models.CharField(max_length=2,primary_key=True)
status = models.BooleanField()
mesa = models.ForeignKey(Reserva)

def __str__(self):
template = 'Asiento {0.asiento} de la mesa {0.mesa}'
return template.format(self)


views.py:



def reservacion(request):
asientos = Asientos.objects.all()
if request.method == "POST":
estatus = Asientos.objects.get(asiento=asientos)
if estatus.status == True:
estatus.status = False
else:
estatus.status = True
estatus.save()

return render(request,"first_app/reservacion.html", {'asientos': asientos})


HTML:



<form enctype="multipart/form-data" action="{% url 'first_app:reservacion' %}"  method="post">
{% csrf_token %}
<div class="row">
{% for asiento in asientos %}
{% if asiento.status %}
<div class="col" ><input class="d-block w-100" value="" name="reservacion" type="image" src="{%static "/img/s6.jpg" %}" >{{asiento.asiento}}</div>
{% else %}
<div class="col" ><input class="d-block w-100" value="" name="reservacion" type="image" src="{%static "/img/sn6.jpg" %}" >{{asiento.asiento}}</div>
{% endif %}
{% if asiento.asiento == '6' %}
</div>
<div class="row">
<div class="col"> </div>
<div class="col"> <img src="{%static "/img/m1.jpg" %}" alt=""> </div>
<div class="col"> </div>
</div>
<div class="row">
{% endif %}

{% endfor %}
</div>
<input type="submit" name="" value="Reservar">
</form>


this code change the value only of the first Asientos.objects.get(asiento=asientos) even when i click another one it just change the value of the first object in my DB.



How can i change the value of the object that i click?










share|improve this question




















  • 1





    Looks that you need some Javascript. Are you familiar with AJAX-calls? I think those would be most convenient here.

    – Anton vBR
    Nov 25 '18 at 6:31


















0















I'm trying to create a view that change a boolean and switch images from it, I already done it but I need to iterate between 12 values (asiento) and i only can point to one of them this is my Django code.



models.py:



class Asientos(models.Model):
asiento = models.CharField(max_length=2,primary_key=True)
status = models.BooleanField()
mesa = models.ForeignKey(Reserva)

def __str__(self):
template = 'Asiento {0.asiento} de la mesa {0.mesa}'
return template.format(self)


views.py:



def reservacion(request):
asientos = Asientos.objects.all()
if request.method == "POST":
estatus = Asientos.objects.get(asiento=asientos)
if estatus.status == True:
estatus.status = False
else:
estatus.status = True
estatus.save()

return render(request,"first_app/reservacion.html", {'asientos': asientos})


HTML:



<form enctype="multipart/form-data" action="{% url 'first_app:reservacion' %}"  method="post">
{% csrf_token %}
<div class="row">
{% for asiento in asientos %}
{% if asiento.status %}
<div class="col" ><input class="d-block w-100" value="" name="reservacion" type="image" src="{%static "/img/s6.jpg" %}" >{{asiento.asiento}}</div>
{% else %}
<div class="col" ><input class="d-block w-100" value="" name="reservacion" type="image" src="{%static "/img/sn6.jpg" %}" >{{asiento.asiento}}</div>
{% endif %}
{% if asiento.asiento == '6' %}
</div>
<div class="row">
<div class="col"> </div>
<div class="col"> <img src="{%static "/img/m1.jpg" %}" alt=""> </div>
<div class="col"> </div>
</div>
<div class="row">
{% endif %}

{% endfor %}
</div>
<input type="submit" name="" value="Reservar">
</form>


this code change the value only of the first Asientos.objects.get(asiento=asientos) even when i click another one it just change the value of the first object in my DB.



How can i change the value of the object that i click?










share|improve this question




















  • 1





    Looks that you need some Javascript. Are you familiar with AJAX-calls? I think those would be most convenient here.

    – Anton vBR
    Nov 25 '18 at 6:31














0












0








0








I'm trying to create a view that change a boolean and switch images from it, I already done it but I need to iterate between 12 values (asiento) and i only can point to one of them this is my Django code.



models.py:



class Asientos(models.Model):
asiento = models.CharField(max_length=2,primary_key=True)
status = models.BooleanField()
mesa = models.ForeignKey(Reserva)

def __str__(self):
template = 'Asiento {0.asiento} de la mesa {0.mesa}'
return template.format(self)


views.py:



def reservacion(request):
asientos = Asientos.objects.all()
if request.method == "POST":
estatus = Asientos.objects.get(asiento=asientos)
if estatus.status == True:
estatus.status = False
else:
estatus.status = True
estatus.save()

return render(request,"first_app/reservacion.html", {'asientos': asientos})


HTML:



<form enctype="multipart/form-data" action="{% url 'first_app:reservacion' %}"  method="post">
{% csrf_token %}
<div class="row">
{% for asiento in asientos %}
{% if asiento.status %}
<div class="col" ><input class="d-block w-100" value="" name="reservacion" type="image" src="{%static "/img/s6.jpg" %}" >{{asiento.asiento}}</div>
{% else %}
<div class="col" ><input class="d-block w-100" value="" name="reservacion" type="image" src="{%static "/img/sn6.jpg" %}" >{{asiento.asiento}}</div>
{% endif %}
{% if asiento.asiento == '6' %}
</div>
<div class="row">
<div class="col"> </div>
<div class="col"> <img src="{%static "/img/m1.jpg" %}" alt=""> </div>
<div class="col"> </div>
</div>
<div class="row">
{% endif %}

{% endfor %}
</div>
<input type="submit" name="" value="Reservar">
</form>


this code change the value only of the first Asientos.objects.get(asiento=asientos) even when i click another one it just change the value of the first object in my DB.



How can i change the value of the object that i click?










share|improve this question
















I'm trying to create a view that change a boolean and switch images from it, I already done it but I need to iterate between 12 values (asiento) and i only can point to one of them this is my Django code.



models.py:



class Asientos(models.Model):
asiento = models.CharField(max_length=2,primary_key=True)
status = models.BooleanField()
mesa = models.ForeignKey(Reserva)

def __str__(self):
template = 'Asiento {0.asiento} de la mesa {0.mesa}'
return template.format(self)


views.py:



def reservacion(request):
asientos = Asientos.objects.all()
if request.method == "POST":
estatus = Asientos.objects.get(asiento=asientos)
if estatus.status == True:
estatus.status = False
else:
estatus.status = True
estatus.save()

return render(request,"first_app/reservacion.html", {'asientos': asientos})


HTML:



<form enctype="multipart/form-data" action="{% url 'first_app:reservacion' %}"  method="post">
{% csrf_token %}
<div class="row">
{% for asiento in asientos %}
{% if asiento.status %}
<div class="col" ><input class="d-block w-100" value="" name="reservacion" type="image" src="{%static "/img/s6.jpg" %}" >{{asiento.asiento}}</div>
{% else %}
<div class="col" ><input class="d-block w-100" value="" name="reservacion" type="image" src="{%static "/img/sn6.jpg" %}" >{{asiento.asiento}}</div>
{% endif %}
{% if asiento.asiento == '6' %}
</div>
<div class="row">
<div class="col"> </div>
<div class="col"> <img src="{%static "/img/m1.jpg" %}" alt=""> </div>
<div class="col"> </div>
</div>
<div class="row">
{% endif %}

{% endfor %}
</div>
<input type="submit" name="" value="Reservar">
</form>


this code change the value only of the first Asientos.objects.get(asiento=asientos) even when i click another one it just change the value of the first object in my DB.



How can i change the value of the object that i click?







python django






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 26 '18 at 6:30







charlie

















asked Nov 25 '18 at 5:39









charliecharlie

34




34








  • 1





    Looks that you need some Javascript. Are you familiar with AJAX-calls? I think those would be most convenient here.

    – Anton vBR
    Nov 25 '18 at 6:31














  • 1





    Looks that you need some Javascript. Are you familiar with AJAX-calls? I think those would be most convenient here.

    – Anton vBR
    Nov 25 '18 at 6:31








1




1





Looks that you need some Javascript. Are you familiar with AJAX-calls? I think those would be most convenient here.

– Anton vBR
Nov 25 '18 at 6:31





Looks that you need some Javascript. Are you familiar with AJAX-calls? I think those would be most convenient here.

– Anton vBR
Nov 25 '18 at 6:31












1 Answer
1






active

oldest

votes


















0














There are multiple way to achieve this. This is probably the most basic:





  1. Change reservacion() to:



    def reservacion(request, asiento_id=None):
    if asiento_id:
    estatus = Asientos.objects.get(pk=asiento_id)
    if estatus.status == True:
    estatus.status = False
    else:
    estatus.status = True
    estatus.save()
    asientos = Asientos.objects.all()
    return render(request,"first_app/reservacion.html", {'asientos ': asientos })



  2. Change url to something like this:



    path('asiento/', views.reservacion, name='asientos'),
    path('asiento/change_status/<int:asiento_id>/', views.reservacion, name='reservacion_status')



  3. Change html to:



    <div class="row">
    {% for asiento in asientos %}
    {% if asiento.status == True %}
    <div class="col">
    <a href="{% url 'reservaction_status' asiento.pk %}" class="d-block w-100">{% static '/img/s6.jpg' %}</a>
    </div>
    {% else %}
    <div class="col">
    <a href="{% url 'reservaction_status' asiento.pk %}" class="d-block w-100">{% static '/img/sn6.jpg' %}</a>
    </div>
    {% endif %}
    {% endfor %}
    </div>



If you want to use POST method, then one fairly basic approach is with Javascript/jQuery.





  1. Change reservacation() to:



     def reservacion(request):
    asientos = Asientos.objects.all()
    if request.method == 'POST':
    asiento_id = request.POST.get('asiento', None)
    if asiento_id:
    estatus = Asientos.objects.get(pk=asiento_id)
    if estatus.status == True:
    estatus.status = False
    else:
    estatus.status = True
    estatus.save()
    return JsonResponse({'status': 'Success', 'msg': 'Status changed'})
    return render(request,"first_app/reservacion.html", {'asientos ': asientos })



  2. Your url is probably right. Should be something like this:



    path('asiento/change_status/', views.reservacion, name='reservacion_status')



  3. Change html to:



    <div class="row">
    {% for asiento in asientos %}
    {% if asiento.status == True%}
    <div class="col"><input class="d-block w-100" type="image" src="{% static '/img/s6.jpg' %}" name="asiento" value="{{ asiento.pk }}"></div>
    {% else %}
    <div class="col"><input class="d-block w-100" type="image" src="{% static '/img/sn6.jpg' %}" name="asiento" value="{{ asiento.pk }}"></div>
    {% endif %}
    {% endfor %}
    </div>
    <script>
    $(document).ready(function() {
    $("[name=asiento]").on("click", function() {
    var formData = {"csrfmiddlewaretoken": "{{ csrf_token }}", "asiento": $(this).val()}
    $.ajax({
    url: "{% url 'reservaction_status' %}",
    method: "POST",
    data: formData,
    success: function(msg) {
    if (msg.status == "Success") {
    location.reload();
    } else {
    alert("Error changing status");
    }
    }
    })
    }
    });
    </script>



I guess that's a good start. This code can be improved in a number of ways, but that's beyond this question.






share|improve this answer


























  • im trying but it doesnt work, if i do it it doesnt shows the objects, now i want to explain this, i already have 12 Asientos.objects.all() in my data base so what i want its to show them as a image and to change its boolean value when the user clicks them, i just cant get every object separated, in the html that you send me it doesnt shows the divs but everything seems to be ok i dont known why it doesnt shows them

    – charlie
    Nov 25 '18 at 18:16













  • If you're not seeing divs, then everything is not ok. Are you sure you used {% for asiento in asientos %} in HTML and included asientos in the context?

    – Borut
    Nov 25 '18 at 18:27











  • yea, now i already have the divs but i can only change the status of the first one, im pointing to asiento_id in estatus but it only takes the first one (it prints the 12 divs and they are clickable but no matter wich one i click it only change the first one), i can even print the id of every one from 1 to 12 but cant get the status of each one

    – charlie
    Nov 25 '18 at 19:26













  • Right, I see. I'll fix the code in the example.

    – Borut
    Nov 25 '18 at 19:38











  • @charlie, I have changed the code for the second example with POST method. I guess that's the one you're trying to implement, You should be able to debug this from here on yourself. I can't really test this code, but it should work.

    – Borut
    Nov 25 '18 at 19:55












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53464967%2fdjango-how-to-use-a-html-tag-attribute-in-views-py%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














There are multiple way to achieve this. This is probably the most basic:





  1. Change reservacion() to:



    def reservacion(request, asiento_id=None):
    if asiento_id:
    estatus = Asientos.objects.get(pk=asiento_id)
    if estatus.status == True:
    estatus.status = False
    else:
    estatus.status = True
    estatus.save()
    asientos = Asientos.objects.all()
    return render(request,"first_app/reservacion.html", {'asientos ': asientos })



  2. Change url to something like this:



    path('asiento/', views.reservacion, name='asientos'),
    path('asiento/change_status/<int:asiento_id>/', views.reservacion, name='reservacion_status')



  3. Change html to:



    <div class="row">
    {% for asiento in asientos %}
    {% if asiento.status == True %}
    <div class="col">
    <a href="{% url 'reservaction_status' asiento.pk %}" class="d-block w-100">{% static '/img/s6.jpg' %}</a>
    </div>
    {% else %}
    <div class="col">
    <a href="{% url 'reservaction_status' asiento.pk %}" class="d-block w-100">{% static '/img/sn6.jpg' %}</a>
    </div>
    {% endif %}
    {% endfor %}
    </div>



If you want to use POST method, then one fairly basic approach is with Javascript/jQuery.





  1. Change reservacation() to:



     def reservacion(request):
    asientos = Asientos.objects.all()
    if request.method == 'POST':
    asiento_id = request.POST.get('asiento', None)
    if asiento_id:
    estatus = Asientos.objects.get(pk=asiento_id)
    if estatus.status == True:
    estatus.status = False
    else:
    estatus.status = True
    estatus.save()
    return JsonResponse({'status': 'Success', 'msg': 'Status changed'})
    return render(request,"first_app/reservacion.html", {'asientos ': asientos })



  2. Your url is probably right. Should be something like this:



    path('asiento/change_status/', views.reservacion, name='reservacion_status')



  3. Change html to:



    <div class="row">
    {% for asiento in asientos %}
    {% if asiento.status == True%}
    <div class="col"><input class="d-block w-100" type="image" src="{% static '/img/s6.jpg' %}" name="asiento" value="{{ asiento.pk }}"></div>
    {% else %}
    <div class="col"><input class="d-block w-100" type="image" src="{% static '/img/sn6.jpg' %}" name="asiento" value="{{ asiento.pk }}"></div>
    {% endif %}
    {% endfor %}
    </div>
    <script>
    $(document).ready(function() {
    $("[name=asiento]").on("click", function() {
    var formData = {"csrfmiddlewaretoken": "{{ csrf_token }}", "asiento": $(this).val()}
    $.ajax({
    url: "{% url 'reservaction_status' %}",
    method: "POST",
    data: formData,
    success: function(msg) {
    if (msg.status == "Success") {
    location.reload();
    } else {
    alert("Error changing status");
    }
    }
    })
    }
    });
    </script>



I guess that's a good start. This code can be improved in a number of ways, but that's beyond this question.






share|improve this answer


























  • im trying but it doesnt work, if i do it it doesnt shows the objects, now i want to explain this, i already have 12 Asientos.objects.all() in my data base so what i want its to show them as a image and to change its boolean value when the user clicks them, i just cant get every object separated, in the html that you send me it doesnt shows the divs but everything seems to be ok i dont known why it doesnt shows them

    – charlie
    Nov 25 '18 at 18:16













  • If you're not seeing divs, then everything is not ok. Are you sure you used {% for asiento in asientos %} in HTML and included asientos in the context?

    – Borut
    Nov 25 '18 at 18:27











  • yea, now i already have the divs but i can only change the status of the first one, im pointing to asiento_id in estatus but it only takes the first one (it prints the 12 divs and they are clickable but no matter wich one i click it only change the first one), i can even print the id of every one from 1 to 12 but cant get the status of each one

    – charlie
    Nov 25 '18 at 19:26













  • Right, I see. I'll fix the code in the example.

    – Borut
    Nov 25 '18 at 19:38











  • @charlie, I have changed the code for the second example with POST method. I guess that's the one you're trying to implement, You should be able to debug this from here on yourself. I can't really test this code, but it should work.

    – Borut
    Nov 25 '18 at 19:55
















0














There are multiple way to achieve this. This is probably the most basic:





  1. Change reservacion() to:



    def reservacion(request, asiento_id=None):
    if asiento_id:
    estatus = Asientos.objects.get(pk=asiento_id)
    if estatus.status == True:
    estatus.status = False
    else:
    estatus.status = True
    estatus.save()
    asientos = Asientos.objects.all()
    return render(request,"first_app/reservacion.html", {'asientos ': asientos })



  2. Change url to something like this:



    path('asiento/', views.reservacion, name='asientos'),
    path('asiento/change_status/<int:asiento_id>/', views.reservacion, name='reservacion_status')



  3. Change html to:



    <div class="row">
    {% for asiento in asientos %}
    {% if asiento.status == True %}
    <div class="col">
    <a href="{% url 'reservaction_status' asiento.pk %}" class="d-block w-100">{% static '/img/s6.jpg' %}</a>
    </div>
    {% else %}
    <div class="col">
    <a href="{% url 'reservaction_status' asiento.pk %}" class="d-block w-100">{% static '/img/sn6.jpg' %}</a>
    </div>
    {% endif %}
    {% endfor %}
    </div>



If you want to use POST method, then one fairly basic approach is with Javascript/jQuery.





  1. Change reservacation() to:



     def reservacion(request):
    asientos = Asientos.objects.all()
    if request.method == 'POST':
    asiento_id = request.POST.get('asiento', None)
    if asiento_id:
    estatus = Asientos.objects.get(pk=asiento_id)
    if estatus.status == True:
    estatus.status = False
    else:
    estatus.status = True
    estatus.save()
    return JsonResponse({'status': 'Success', 'msg': 'Status changed'})
    return render(request,"first_app/reservacion.html", {'asientos ': asientos })



  2. Your url is probably right. Should be something like this:



    path('asiento/change_status/', views.reservacion, name='reservacion_status')



  3. Change html to:



    <div class="row">
    {% for asiento in asientos %}
    {% if asiento.status == True%}
    <div class="col"><input class="d-block w-100" type="image" src="{% static '/img/s6.jpg' %}" name="asiento" value="{{ asiento.pk }}"></div>
    {% else %}
    <div class="col"><input class="d-block w-100" type="image" src="{% static '/img/sn6.jpg' %}" name="asiento" value="{{ asiento.pk }}"></div>
    {% endif %}
    {% endfor %}
    </div>
    <script>
    $(document).ready(function() {
    $("[name=asiento]").on("click", function() {
    var formData = {"csrfmiddlewaretoken": "{{ csrf_token }}", "asiento": $(this).val()}
    $.ajax({
    url: "{% url 'reservaction_status' %}",
    method: "POST",
    data: formData,
    success: function(msg) {
    if (msg.status == "Success") {
    location.reload();
    } else {
    alert("Error changing status");
    }
    }
    })
    }
    });
    </script>



I guess that's a good start. This code can be improved in a number of ways, but that's beyond this question.






share|improve this answer


























  • im trying but it doesnt work, if i do it it doesnt shows the objects, now i want to explain this, i already have 12 Asientos.objects.all() in my data base so what i want its to show them as a image and to change its boolean value when the user clicks them, i just cant get every object separated, in the html that you send me it doesnt shows the divs but everything seems to be ok i dont known why it doesnt shows them

    – charlie
    Nov 25 '18 at 18:16













  • If you're not seeing divs, then everything is not ok. Are you sure you used {% for asiento in asientos %} in HTML and included asientos in the context?

    – Borut
    Nov 25 '18 at 18:27











  • yea, now i already have the divs but i can only change the status of the first one, im pointing to asiento_id in estatus but it only takes the first one (it prints the 12 divs and they are clickable but no matter wich one i click it only change the first one), i can even print the id of every one from 1 to 12 but cant get the status of each one

    – charlie
    Nov 25 '18 at 19:26













  • Right, I see. I'll fix the code in the example.

    – Borut
    Nov 25 '18 at 19:38











  • @charlie, I have changed the code for the second example with POST method. I guess that's the one you're trying to implement, You should be able to debug this from here on yourself. I can't really test this code, but it should work.

    – Borut
    Nov 25 '18 at 19:55














0












0








0







There are multiple way to achieve this. This is probably the most basic:





  1. Change reservacion() to:



    def reservacion(request, asiento_id=None):
    if asiento_id:
    estatus = Asientos.objects.get(pk=asiento_id)
    if estatus.status == True:
    estatus.status = False
    else:
    estatus.status = True
    estatus.save()
    asientos = Asientos.objects.all()
    return render(request,"first_app/reservacion.html", {'asientos ': asientos })



  2. Change url to something like this:



    path('asiento/', views.reservacion, name='asientos'),
    path('asiento/change_status/<int:asiento_id>/', views.reservacion, name='reservacion_status')



  3. Change html to:



    <div class="row">
    {% for asiento in asientos %}
    {% if asiento.status == True %}
    <div class="col">
    <a href="{% url 'reservaction_status' asiento.pk %}" class="d-block w-100">{% static '/img/s6.jpg' %}</a>
    </div>
    {% else %}
    <div class="col">
    <a href="{% url 'reservaction_status' asiento.pk %}" class="d-block w-100">{% static '/img/sn6.jpg' %}</a>
    </div>
    {% endif %}
    {% endfor %}
    </div>



If you want to use POST method, then one fairly basic approach is with Javascript/jQuery.





  1. Change reservacation() to:



     def reservacion(request):
    asientos = Asientos.objects.all()
    if request.method == 'POST':
    asiento_id = request.POST.get('asiento', None)
    if asiento_id:
    estatus = Asientos.objects.get(pk=asiento_id)
    if estatus.status == True:
    estatus.status = False
    else:
    estatus.status = True
    estatus.save()
    return JsonResponse({'status': 'Success', 'msg': 'Status changed'})
    return render(request,"first_app/reservacion.html", {'asientos ': asientos })



  2. Your url is probably right. Should be something like this:



    path('asiento/change_status/', views.reservacion, name='reservacion_status')



  3. Change html to:



    <div class="row">
    {% for asiento in asientos %}
    {% if asiento.status == True%}
    <div class="col"><input class="d-block w-100" type="image" src="{% static '/img/s6.jpg' %}" name="asiento" value="{{ asiento.pk }}"></div>
    {% else %}
    <div class="col"><input class="d-block w-100" type="image" src="{% static '/img/sn6.jpg' %}" name="asiento" value="{{ asiento.pk }}"></div>
    {% endif %}
    {% endfor %}
    </div>
    <script>
    $(document).ready(function() {
    $("[name=asiento]").on("click", function() {
    var formData = {"csrfmiddlewaretoken": "{{ csrf_token }}", "asiento": $(this).val()}
    $.ajax({
    url: "{% url 'reservaction_status' %}",
    method: "POST",
    data: formData,
    success: function(msg) {
    if (msg.status == "Success") {
    location.reload();
    } else {
    alert("Error changing status");
    }
    }
    })
    }
    });
    </script>



I guess that's a good start. This code can be improved in a number of ways, but that's beyond this question.






share|improve this answer















There are multiple way to achieve this. This is probably the most basic:





  1. Change reservacion() to:



    def reservacion(request, asiento_id=None):
    if asiento_id:
    estatus = Asientos.objects.get(pk=asiento_id)
    if estatus.status == True:
    estatus.status = False
    else:
    estatus.status = True
    estatus.save()
    asientos = Asientos.objects.all()
    return render(request,"first_app/reservacion.html", {'asientos ': asientos })



  2. Change url to something like this:



    path('asiento/', views.reservacion, name='asientos'),
    path('asiento/change_status/<int:asiento_id>/', views.reservacion, name='reservacion_status')



  3. Change html to:



    <div class="row">
    {% for asiento in asientos %}
    {% if asiento.status == True %}
    <div class="col">
    <a href="{% url 'reservaction_status' asiento.pk %}" class="d-block w-100">{% static '/img/s6.jpg' %}</a>
    </div>
    {% else %}
    <div class="col">
    <a href="{% url 'reservaction_status' asiento.pk %}" class="d-block w-100">{% static '/img/sn6.jpg' %}</a>
    </div>
    {% endif %}
    {% endfor %}
    </div>



If you want to use POST method, then one fairly basic approach is with Javascript/jQuery.





  1. Change reservacation() to:



     def reservacion(request):
    asientos = Asientos.objects.all()
    if request.method == 'POST':
    asiento_id = request.POST.get('asiento', None)
    if asiento_id:
    estatus = Asientos.objects.get(pk=asiento_id)
    if estatus.status == True:
    estatus.status = False
    else:
    estatus.status = True
    estatus.save()
    return JsonResponse({'status': 'Success', 'msg': 'Status changed'})
    return render(request,"first_app/reservacion.html", {'asientos ': asientos })



  2. Your url is probably right. Should be something like this:



    path('asiento/change_status/', views.reservacion, name='reservacion_status')



  3. Change html to:



    <div class="row">
    {% for asiento in asientos %}
    {% if asiento.status == True%}
    <div class="col"><input class="d-block w-100" type="image" src="{% static '/img/s6.jpg' %}" name="asiento" value="{{ asiento.pk }}"></div>
    {% else %}
    <div class="col"><input class="d-block w-100" type="image" src="{% static '/img/sn6.jpg' %}" name="asiento" value="{{ asiento.pk }}"></div>
    {% endif %}
    {% endfor %}
    </div>
    <script>
    $(document).ready(function() {
    $("[name=asiento]").on("click", function() {
    var formData = {"csrfmiddlewaretoken": "{{ csrf_token }}", "asiento": $(this).val()}
    $.ajax({
    url: "{% url 'reservaction_status' %}",
    method: "POST",
    data: formData,
    success: function(msg) {
    if (msg.status == "Success") {
    location.reload();
    } else {
    alert("Error changing status");
    }
    }
    })
    }
    });
    </script>



I guess that's a good start. This code can be improved in a number of ways, but that's beyond this question.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 26 '18 at 17:35

























answered Nov 25 '18 at 11:32









BorutBorut

1,814259




1,814259













  • im trying but it doesnt work, if i do it it doesnt shows the objects, now i want to explain this, i already have 12 Asientos.objects.all() in my data base so what i want its to show them as a image and to change its boolean value when the user clicks them, i just cant get every object separated, in the html that you send me it doesnt shows the divs but everything seems to be ok i dont known why it doesnt shows them

    – charlie
    Nov 25 '18 at 18:16













  • If you're not seeing divs, then everything is not ok. Are you sure you used {% for asiento in asientos %} in HTML and included asientos in the context?

    – Borut
    Nov 25 '18 at 18:27











  • yea, now i already have the divs but i can only change the status of the first one, im pointing to asiento_id in estatus but it only takes the first one (it prints the 12 divs and they are clickable but no matter wich one i click it only change the first one), i can even print the id of every one from 1 to 12 but cant get the status of each one

    – charlie
    Nov 25 '18 at 19:26













  • Right, I see. I'll fix the code in the example.

    – Borut
    Nov 25 '18 at 19:38











  • @charlie, I have changed the code for the second example with POST method. I guess that's the one you're trying to implement, You should be able to debug this from here on yourself. I can't really test this code, but it should work.

    – Borut
    Nov 25 '18 at 19:55



















  • im trying but it doesnt work, if i do it it doesnt shows the objects, now i want to explain this, i already have 12 Asientos.objects.all() in my data base so what i want its to show them as a image and to change its boolean value when the user clicks them, i just cant get every object separated, in the html that you send me it doesnt shows the divs but everything seems to be ok i dont known why it doesnt shows them

    – charlie
    Nov 25 '18 at 18:16













  • If you're not seeing divs, then everything is not ok. Are you sure you used {% for asiento in asientos %} in HTML and included asientos in the context?

    – Borut
    Nov 25 '18 at 18:27











  • yea, now i already have the divs but i can only change the status of the first one, im pointing to asiento_id in estatus but it only takes the first one (it prints the 12 divs and they are clickable but no matter wich one i click it only change the first one), i can even print the id of every one from 1 to 12 but cant get the status of each one

    – charlie
    Nov 25 '18 at 19:26













  • Right, I see. I'll fix the code in the example.

    – Borut
    Nov 25 '18 at 19:38











  • @charlie, I have changed the code for the second example with POST method. I guess that's the one you're trying to implement, You should be able to debug this from here on yourself. I can't really test this code, but it should work.

    – Borut
    Nov 25 '18 at 19:55

















im trying but it doesnt work, if i do it it doesnt shows the objects, now i want to explain this, i already have 12 Asientos.objects.all() in my data base so what i want its to show them as a image and to change its boolean value when the user clicks them, i just cant get every object separated, in the html that you send me it doesnt shows the divs but everything seems to be ok i dont known why it doesnt shows them

– charlie
Nov 25 '18 at 18:16







im trying but it doesnt work, if i do it it doesnt shows the objects, now i want to explain this, i already have 12 Asientos.objects.all() in my data base so what i want its to show them as a image and to change its boolean value when the user clicks them, i just cant get every object separated, in the html that you send me it doesnt shows the divs but everything seems to be ok i dont known why it doesnt shows them

– charlie
Nov 25 '18 at 18:16















If you're not seeing divs, then everything is not ok. Are you sure you used {% for asiento in asientos %} in HTML and included asientos in the context?

– Borut
Nov 25 '18 at 18:27





If you're not seeing divs, then everything is not ok. Are you sure you used {% for asiento in asientos %} in HTML and included asientos in the context?

– Borut
Nov 25 '18 at 18:27













yea, now i already have the divs but i can only change the status of the first one, im pointing to asiento_id in estatus but it only takes the first one (it prints the 12 divs and they are clickable but no matter wich one i click it only change the first one), i can even print the id of every one from 1 to 12 but cant get the status of each one

– charlie
Nov 25 '18 at 19:26







yea, now i already have the divs but i can only change the status of the first one, im pointing to asiento_id in estatus but it only takes the first one (it prints the 12 divs and they are clickable but no matter wich one i click it only change the first one), i can even print the id of every one from 1 to 12 but cant get the status of each one

– charlie
Nov 25 '18 at 19:26















Right, I see. I'll fix the code in the example.

– Borut
Nov 25 '18 at 19:38





Right, I see. I'll fix the code in the example.

– Borut
Nov 25 '18 at 19:38













@charlie, I have changed the code for the second example with POST method. I guess that's the one you're trying to implement, You should be able to debug this from here on yourself. I can't really test this code, but it should work.

– Borut
Nov 25 '18 at 19:55





@charlie, I have changed the code for the second example with POST method. I guess that's the one you're trying to implement, You should be able to debug this from here on yourself. I can't really test this code, but it should work.

– Borut
Nov 25 '18 at 19:55




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53464967%2fdjango-how-to-use-a-html-tag-attribute-in-views-py%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Post-Redirect-Get with Spring WebFlux and Thymeleaf

Xamarin.form Move up view when keyboard appear

JBPM : POST request for execute process go wrong