0

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.

1

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Ok I got it I tried using plain javascript and that too worked out so I will use your code and see if it can make it mode efficient. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.