簡體   English   中英

如何使用 django 代碼更改 html 背景顏色

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

我正在做一個項目,我想知道,我想在 HTML 中制作一個按鈕,它將在 Django views.py 中進行控制。 所以基本上當有人點擊按鈕時背景變暗並且它被保存,我的意思是如果這個人刷新頁面背景仍然是黑暗的。 我想知道是否有可能做到這一點。

謝謝。

這是很容易做到的。 按鈕點擊可以連接到 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'})

現在剩下的就是確保您的 html 將背景顏色設置為引用 Model 實例的變量,您在 Ajax 調用中保存了顏色

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM