I'm trying to use a Django signal to toggle a model's boolean value to False from True when a button is clicked. I think that the Django sender would be the button click and the receiver would be the function that changes the boolean value. I'm not sure how to write out a button click as a signal sender however.
Here is my model with the Boolean value.
From models.py:
class User(AbstractUser):
is_blue = models.BooleanField(default=False)
Any thoughts on a what a signal would look like that take a button click and changes this value to True?
To change your model field, you need to create a separate function for it in your views, e.g.:
from django.http import JsonResponse
from xxx.models import User
def ajax_change_user(request):
is_blue= request.GET.get('is_blue', False)
# Get your User model
user = User.objects.get(pk=user_id)
try:
is_blue = True
user.save()
return JsonResponse({"success": True})
except Exception as e:
return JsonResponse({"success": False})
return JsonResponse(data)
Then you need to add a url for this view:
path('ajax/change_user', views.ajax_change_user, name='ajax_change_user')
Then in your html, you need to add a tag with the necessary class, e.g.:
{% csrf_token %}
<a href="javascript:" class="change-user btn" data-userid="{{user.pk}}">Change</a>
And then finally the javascript with ajax call part:
<script>
$(".change-user").on('click', function () {
var user_id = $(this).data('userid);
var is_blue = False # say you start with the status being false
$.ajax({
url: '/ajax/change_user/',
data: {
'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(),
'is_blue': is_blue
'user_id': user_id
},
dataType: 'json',
success: function (data) {
if (data.success) {
alert("ajax call was successful.");
is_blue = True # if button is clicked, make 'is_blue' True
}else{
alert("ajax call was not successful.");
}
}
});
});
</script>
This is just an example to get you started, you would need to alter it to suit your needs. You could for example add an if statement before the ajax call to check if is_blue
is true or not, so that you can toggle the value.