简体   繁体   English

如何使用 django 代码更改 html 背景颜色

[英]How to change html background color using django code

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.我正在做一个项目,我想知道,我想在 HTML 中制作一个按钮,它将在 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.谢谢。

This is very easily doable.这是很容易做到的。 The button click could be connected to a jquery click function which also includes an ajax call:按钮点击可以连接到 jquery 点击 function,其中还包括 ajax 呼叫:

$('#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现在剩下的就是确保您的 html 将背景颜色设置为引用 Model 实例的变量,您在 Ajax 调用中保存了颜色

<body style='background-color:{{bg_color}}'></body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM