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

2024-06-17 13:01:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个项目,我想知道,我想用HTML制作一个按钮,它可以在Django views.py中控制。基本上,当有人点击按钮时,背景会变暗并保存下来,我的意思是,如果有人刷新页面,背景仍然会变暗。我想知道是否有可能做到这一点

谢谢


Tags: 项目djangopyhtml页面按钮views背景
1条回答
网友
1楼 · 发布于 2024-06-17 13:01:41

这是很容易做到的。按钮单击可以连接到jquery单击函数,该函数还包括一个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'})

现在只剩下确保html的背景颜色设置为一个变量,该变量引用在Ajax调用中保存颜色的模型实例

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

相关问题 更多 >