2017-05-23 40 views
0

我想創建一個添加到收藏夾功能,到目前爲止,我設法顯示一個帶有圖標的按鈕,如果字段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(); 
}); 
+0

你有一個python API公開數據庫的方式允許Ajax與它通信嗎?如果是這樣,您可以將一個單擊事件綁定到該按鈕,然後編寫jquery將JSON對象發佈到您的Python API終點,然後寫入數據庫。 – JacobIRR

+0

Hello @JacobIRR感謝您的輸入,您指的是REST API的權利?我會盡力將其實現到我的代碼中。謝謝。 –

+0

@Nazkter已經領先於我。這個答案就是我所提出的建議的實施。 – JacobIRR

回答

1

可以使一個AJAX調用在你的Django服務器的一種服務。

首先,你需要做一個URL來獲取AJAX請願書(urls.py):

url(r'^ajax_is_favorite/$', views.ajax_is_favorite, name='ajax_is_favorite'), 

接下來,你需要添加一個函數來解決上訪(views.py):

def ajax_is_favorite(request): 
    if not request.is_ajax() or not request.method=='POST': 
     return HttpResponseNotAllowed(['POST']) 
    else: 
     #Here you have to get the data and update the object 
     return HttpResponse({"success":True}) 

最後,你需要做一個Ajax功能,在您的模板,使該服務的調用:

$.ajax({ 
    url : "{% url 'ajax_is_favorite'%}", 
    data: { 
     'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(), 
     'ProjectProfileID': 'here you get the id', 
     'isFavorite':true //or false 
    }, 
    type : 'POST', 
    dataType : 'json', 
    success : function(json) { 
     if(json.success === true){ 
      // do somthing 
     }else{ 
      // do somthing 
     } 
    } 
}); 

沒有做t忘記在模板中添加{%csrf_token%}標籤,這對於請求是必要的。

+0

嗨@Nazkter,感謝您的輸入,這是我昨天基於新波士頓示例項目嘗試的,但有點令人困惑。謝謝你爲我簡化這個。我會立即執行此操作,如果有的話我會盡快回復 –

+0

@ M.Izzat請在當時提問,您刪除了主要問題,並將"可選"作爲新問題。請回復您的更改,如果我的答案有效,您可以將其設置爲正確的答案,並最終爲其他問題打開其他問題。 – Nazkter

+0

我的歉意我生病改變了這個問題,我意識到,stackoverflow有多少個問題,你可以問的限制,因爲它在同一主題,我想我改變它,感謝您的幫助,併爲不方便 –