我想創建一個添加到收藏夾功能,到目前爲止,我設法顯示一個帶有圖標的按鈕,如果字段is_favorite
但我無法更新我的數據庫。(Django/HTML)如何創建添加到收藏夾功能
我的問題是:我怎樣才能改變收藏狀態,並更新到我的數據庫而無需刷新頁面
編輯: [解決]感謝@Nazkter和巴基羅伯特項目。我編輯下面
這裏是我的代碼工作代碼:
model.py
class ProjectProfile(models.Model):
project_name = models.CharField(max_length=100)
artist = models.CharField(max_length=100)
is_favorite = models.BooleanField(default=False)
def __str__(self):
return self.project_name
views.py
def index_view(request):
context = {
"table_list": ProjectProfile.objects.all(),
"title": "Table_List"
}
return render(request, 'index.html', context)
def favorite_project(request, projectprofile_id):
projectprofile = get_object_or_404(ProjectProfile, pk=projectprofile_id)
try:
if projectprofile.is_favorite:
projectprofile.is_favorite = False
else:
projectprofile.is_favorite = True
projectprofile.save()
except (KeyError, ProjectProfile.DoesNotExist):
return JsonResponse({'success': False})
else:
return JsonResponse({'success': True})
url.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', index_view, name='index_view'),
url(r'^(?P<projectprofile_id>[0-9]+)/favorite_album/$', favorite_project, name='favorite_project'),
]
指數。 html
<head>
<meta charset="UTF-8">
<title>Favorite function</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link href='https://fonts.googleapis.com/css?family=Satisfy' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Favorite Function</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Artist</th>
<th>Favorite</th>
</tr>
</thead>
<tbody>
{% for data in table_list %}{% csrf_token %}
<tr >
<td>{{data.project_name}}</td>
<td>{{data.artist}}</td>
<!-- Favorite Album -->
<td><a href="{% url 'favorite_project' data.id %}" class="btn btn-default btn-sm btn-favorite" role="button"><span class=" glyphicon glyphicon-star {% if data.is_favorite %}active{% endif %}" action=""></span></a></td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
的JavaScript
var ProjectListPage = {
init: function() {
this.$container = $('.project-container');
this.render();
this.bindEvents();
},
render: function() {
},
bindEvents: function() {
$('.btn-favorite', this.$container).on('click', function(e) {
console.log('Hola');
e.preventDefault();
var self = $(this);
var url = $(this).attr('href');
$.getJSON(url, function(result) {
if (result.success) {
$('.glyphicon-star', self).toggleClass('active');
}
});
return false;
});
}
};
$(document).ready(function() {
ProjectListPage.init();
});
你有一個python API公開數據庫的方式允許Ajax與它通信嗎?如果是這樣,您可以將一個單擊事件綁定到該按鈕,然後編寫jquery將JSON對象發佈到您的Python API終點,然後寫入數據庫。 – JacobIRR
Hello @JacobIRR感謝您的輸入,您指的是REST API的權利?我會盡力將其實現到我的代碼中。謝謝。 –
@Nazkter已經領先於我。這個答案就是我所提出的建議的實施。 – JacobIRR