I was doing a project and I was wondering, I wanted to make a button in HTML which would be controlled in the Django views.py. So basically when someone clicks on the button the background becomes dark and it gets saved, what I mean is if the person refreshes the page the background will still be dark. I wanted to know if it was possible to do it.
Thanks.
CodePudding user response:
This is very easily doable. The button click could be connected to a jquery click function which also includes an ajax call:
$('#id_button).click(function(){
$('body').css({'background-color': 'dark-gray'})
$.post({% url 'change-background-color' %}, {color: 'dark-gray'}, function(){
location.reload() // to refresh the page with new background color
})
})
# urls.py
add the following path
path('change-background-color/', views.change_background_color, name='change-background-color'),
# views.py
add the following view
def change_background_color(request):
color = request.POST.get('color')
# you could save the input to a model BackgroundColor as an instance or
update a current record.
# creating an instance
BackgroundColor.objects.create(bg_color=color)
return JsonResponse({'response': 'successfully changed color'})
Now all that is left is to ensure that your html has background color set to a variable referring to the Model instance where you saved the color in Ajax call
<body style='background-color:{{bg_color}}'></body>