Change a boolean value after a click on a button in Django











up vote
0
down vote

favorite
1












I need some help regarding button clicks and boolean value changes.



My model:



class Topic(models.Model):
subject = models.CharField(max_length=255)
category = models.CharField(max_length=255)
last_updated = models.DateTimeField(auto_now_add=True)
starter = models.ForeignKey(User, on_delete=models.CASCADE, related_name='topics')
slug = models.SlugField(unique=True)
isReported = models.BooleanField(default=False)
startPrice = models.IntegerField(validators=[RegexValidator(r'^d{1,10}$')])


I want to change the state of the field "isReported" from the default value "False" to "True" after a click on a button:



<button type="submit" class="btn btn-primary btn-block">Report</button>


I already googled and found something like this on SO (How do I change a value in django on button click in HTML?) but I am lacking knowledge of the concept presented in this thread. Unfortunately this was the only helpful information I could find.



How can I change the boolean value in my database after a single button click? It is not neccessary to change the value back on this button.



I somehome tried to adapt the code of the link:



views.py:



def ajax_change_status(request):
isReported = request.GET.get('isReported', False)
pk = request.GET.get('pk', False)
# first you get your Job model
job = Topic.objects.get(pk=pk)
try:
job.isReported = isReported
job.save()
return JsonResponse({"success": True})
except Exception as e:
return JsonResponse({"success": False})
return JsonResponse(data)


xxx.html:



    <form method="post" novalidate>
{% csrf_token %}
<button type="submit" class="btn btn-danger btn-sm" id="change" role="button">Report</button>
</form>




<script>
$("#change").on('click', function () {

var pk = '{{ topic.pk }}'
var isReported = 'True'

$.ajax({
url: '/ajax/change_status/',
data: {
'isReported': isReported
'pk': pk
},
dataType: 'json',
success: function (data) {
if (data.success) {
alert("ajax call success.");
// here you update the HTML to change the active to innactive
}else{
alert("ajax call not success.");
}
}
});

});




I am trying to understand the concept, but (obv.) it is not working.



POST /request/xxx-xxx-xxx-5622149-3/ HTTP/1.0" 200 5472









share|improve this question
























  • The answer on the thread you linked solves your problem perfectly. Can you expand on the concept(s) you don't understand?
    – v25
    Nov 7 at 20:25










  • hi v25, I edited the code with my adapted version. Any input appreciated!
    – JohnDole
    Nov 7 at 21:14










  • Firstly, in the javascrpit snippet, keep the line 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(), as the AJAX request needs to pass this back for security reasons. However it's not obvious what's not working, as you haven't really posted any error traceback. The last line you added looks like a sucessful HTTP response (200). Are you seeing an error elsewhere?
    – v25
    Nov 7 at 21:24

















up vote
0
down vote

favorite
1












I need some help regarding button clicks and boolean value changes.



My model:



class Topic(models.Model):
subject = models.CharField(max_length=255)
category = models.CharField(max_length=255)
last_updated = models.DateTimeField(auto_now_add=True)
starter = models.ForeignKey(User, on_delete=models.CASCADE, related_name='topics')
slug = models.SlugField(unique=True)
isReported = models.BooleanField(default=False)
startPrice = models.IntegerField(validators=[RegexValidator(r'^d{1,10}$')])


I want to change the state of the field "isReported" from the default value "False" to "True" after a click on a button:



<button type="submit" class="btn btn-primary btn-block">Report</button>


I already googled and found something like this on SO (How do I change a value in django on button click in HTML?) but I am lacking knowledge of the concept presented in this thread. Unfortunately this was the only helpful information I could find.



How can I change the boolean value in my database after a single button click? It is not neccessary to change the value back on this button.



I somehome tried to adapt the code of the link:



views.py:



def ajax_change_status(request):
isReported = request.GET.get('isReported', False)
pk = request.GET.get('pk', False)
# first you get your Job model
job = Topic.objects.get(pk=pk)
try:
job.isReported = isReported
job.save()
return JsonResponse({"success": True})
except Exception as e:
return JsonResponse({"success": False})
return JsonResponse(data)


xxx.html:



    <form method="post" novalidate>
{% csrf_token %}
<button type="submit" class="btn btn-danger btn-sm" id="change" role="button">Report</button>
</form>




<script>
$("#change").on('click', function () {

var pk = '{{ topic.pk }}'
var isReported = 'True'

$.ajax({
url: '/ajax/change_status/',
data: {
'isReported': isReported
'pk': pk
},
dataType: 'json',
success: function (data) {
if (data.success) {
alert("ajax call success.");
// here you update the HTML to change the active to innactive
}else{
alert("ajax call not success.");
}
}
});

});




I am trying to understand the concept, but (obv.) it is not working.



POST /request/xxx-xxx-xxx-5622149-3/ HTTP/1.0" 200 5472









share|improve this question
























  • The answer on the thread you linked solves your problem perfectly. Can you expand on the concept(s) you don't understand?
    – v25
    Nov 7 at 20:25










  • hi v25, I edited the code with my adapted version. Any input appreciated!
    – JohnDole
    Nov 7 at 21:14










  • Firstly, in the javascrpit snippet, keep the line 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(), as the AJAX request needs to pass this back for security reasons. However it's not obvious what's not working, as you haven't really posted any error traceback. The last line you added looks like a sucessful HTTP response (200). Are you seeing an error elsewhere?
    – v25
    Nov 7 at 21:24















up vote
0
down vote

favorite
1









up vote
0
down vote

favorite
1






1





I need some help regarding button clicks and boolean value changes.



My model:



class Topic(models.Model):
subject = models.CharField(max_length=255)
category = models.CharField(max_length=255)
last_updated = models.DateTimeField(auto_now_add=True)
starter = models.ForeignKey(User, on_delete=models.CASCADE, related_name='topics')
slug = models.SlugField(unique=True)
isReported = models.BooleanField(default=False)
startPrice = models.IntegerField(validators=[RegexValidator(r'^d{1,10}$')])


I want to change the state of the field "isReported" from the default value "False" to "True" after a click on a button:



<button type="submit" class="btn btn-primary btn-block">Report</button>


I already googled and found something like this on SO (How do I change a value in django on button click in HTML?) but I am lacking knowledge of the concept presented in this thread. Unfortunately this was the only helpful information I could find.



How can I change the boolean value in my database after a single button click? It is not neccessary to change the value back on this button.



I somehome tried to adapt the code of the link:



views.py:



def ajax_change_status(request):
isReported = request.GET.get('isReported', False)
pk = request.GET.get('pk', False)
# first you get your Job model
job = Topic.objects.get(pk=pk)
try:
job.isReported = isReported
job.save()
return JsonResponse({"success": True})
except Exception as e:
return JsonResponse({"success": False})
return JsonResponse(data)


xxx.html:



    <form method="post" novalidate>
{% csrf_token %}
<button type="submit" class="btn btn-danger btn-sm" id="change" role="button">Report</button>
</form>




<script>
$("#change").on('click', function () {

var pk = '{{ topic.pk }}'
var isReported = 'True'

$.ajax({
url: '/ajax/change_status/',
data: {
'isReported': isReported
'pk': pk
},
dataType: 'json',
success: function (data) {
if (data.success) {
alert("ajax call success.");
// here you update the HTML to change the active to innactive
}else{
alert("ajax call not success.");
}
}
});

});




I am trying to understand the concept, but (obv.) it is not working.



POST /request/xxx-xxx-xxx-5622149-3/ HTTP/1.0" 200 5472









share|improve this question















I need some help regarding button clicks and boolean value changes.



My model:



class Topic(models.Model):
subject = models.CharField(max_length=255)
category = models.CharField(max_length=255)
last_updated = models.DateTimeField(auto_now_add=True)
starter = models.ForeignKey(User, on_delete=models.CASCADE, related_name='topics')
slug = models.SlugField(unique=True)
isReported = models.BooleanField(default=False)
startPrice = models.IntegerField(validators=[RegexValidator(r'^d{1,10}$')])


I want to change the state of the field "isReported" from the default value "False" to "True" after a click on a button:



<button type="submit" class="btn btn-primary btn-block">Report</button>


I already googled and found something like this on SO (How do I change a value in django on button click in HTML?) but I am lacking knowledge of the concept presented in this thread. Unfortunately this was the only helpful information I could find.



How can I change the boolean value in my database after a single button click? It is not neccessary to change the value back on this button.



I somehome tried to adapt the code of the link:



views.py:



def ajax_change_status(request):
isReported = request.GET.get('isReported', False)
pk = request.GET.get('pk', False)
# first you get your Job model
job = Topic.objects.get(pk=pk)
try:
job.isReported = isReported
job.save()
return JsonResponse({"success": True})
except Exception as e:
return JsonResponse({"success": False})
return JsonResponse(data)


xxx.html:



    <form method="post" novalidate>
{% csrf_token %}
<button type="submit" class="btn btn-danger btn-sm" id="change" role="button">Report</button>
</form>




<script>
$("#change").on('click', function () {

var pk = '{{ topic.pk }}'
var isReported = 'True'

$.ajax({
url: '/ajax/change_status/',
data: {
'isReported': isReported
'pk': pk
},
dataType: 'json',
success: function (data) {
if (data.success) {
alert("ajax call success.");
// here you update the HTML to change the active to innactive
}else{
alert("ajax call not success.");
}
}
});

});




I am trying to understand the concept, but (obv.) it is not working.



POST /request/xxx-xxx-xxx-5622149-3/ HTTP/1.0" 200 5472






ajax django button boolean






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 7 at 21:13

























asked Nov 7 at 19:07









JohnDole

356




356












  • The answer on the thread you linked solves your problem perfectly. Can you expand on the concept(s) you don't understand?
    – v25
    Nov 7 at 20:25










  • hi v25, I edited the code with my adapted version. Any input appreciated!
    – JohnDole
    Nov 7 at 21:14










  • Firstly, in the javascrpit snippet, keep the line 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(), as the AJAX request needs to pass this back for security reasons. However it's not obvious what's not working, as you haven't really posted any error traceback. The last line you added looks like a sucessful HTTP response (200). Are you seeing an error elsewhere?
    – v25
    Nov 7 at 21:24




















  • The answer on the thread you linked solves your problem perfectly. Can you expand on the concept(s) you don't understand?
    – v25
    Nov 7 at 20:25










  • hi v25, I edited the code with my adapted version. Any input appreciated!
    – JohnDole
    Nov 7 at 21:14










  • Firstly, in the javascrpit snippet, keep the line 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(), as the AJAX request needs to pass this back for security reasons. However it's not obvious what's not working, as you haven't really posted any error traceback. The last line you added looks like a sucessful HTTP response (200). Are you seeing an error elsewhere?
    – v25
    Nov 7 at 21:24


















The answer on the thread you linked solves your problem perfectly. Can you expand on the concept(s) you don't understand?
– v25
Nov 7 at 20:25




The answer on the thread you linked solves your problem perfectly. Can you expand on the concept(s) you don't understand?
– v25
Nov 7 at 20:25












hi v25, I edited the code with my adapted version. Any input appreciated!
– JohnDole
Nov 7 at 21:14




hi v25, I edited the code with my adapted version. Any input appreciated!
– JohnDole
Nov 7 at 21:14












Firstly, in the javascrpit snippet, keep the line 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(), as the AJAX request needs to pass this back for security reasons. However it's not obvious what's not working, as you haven't really posted any error traceback. The last line you added looks like a sucessful HTTP response (200). Are you seeing an error elsewhere?
– v25
Nov 7 at 21:24






Firstly, in the javascrpit snippet, keep the line 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(), as the AJAX request needs to pass this back for security reasons. However it's not obvious what's not working, as you haven't really posted any error traceback. The last line you added looks like a sucessful HTTP response (200). Are you seeing an error elsewhere?
– v25
Nov 7 at 21:24



















active

oldest

votes











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',
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%2f53196177%2fchange-a-boolean-value-after-a-click-on-a-button-in-django%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















 

draft saved


draft discarded



















































 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53196177%2fchange-a-boolean-value-after-a-click-on-a-button-in-django%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







這個網誌中的熱門文章

Xamarin.form Move up view when keyboard appear

Post-Redirect-Get with Spring WebFlux and Thymeleaf

Anylogic : not able to use stopDelay()