2012-12-22 9 views
12

तो मैं एक अजाक्स कॉल में इस दृश्य बदल परेशानी हो रही किया गया है:मेरा खुद का पसंद बटन: Django + Ajax - कैसे?

def company_single(request, slug): 
    company = get_object_or_404(CompanyProfile, slug=slug) 
    company_list = CompanyProfile.objects.get(slug=slug) 

    try: 
     tcompany = CompanyLikes.objects.get(company=company_list) 
     total_likes = tcompany.likes 
     user_liked = CompanyLikes.objects.get(user=request.user) 
    except: 
     total_likes = 0 


    instance, created = CompanyLikes.objects.get_or_create(company=company_list) 
    likes_form = CompanyLikesForm(request.POST or None, instance=instance) 

    if likes_form.is_valid(): 
     this = likes_form.save(commit=False) 
     try:  
      if user_liked: 
       this.likes -=1 
       this.user.remove(request.user) 
     except: 
      this.user.add(request.user) 
      this.likes += 1 
     this.save() 

    return render_to_response('company.html', locals(), context_instance=RequestContext(request)) 

मुझे लगता है मैं jQuery और JSON की जरूरत है, लेकिन मुझे यकीन है कि इसे यहाँ कैसे लागू करने के लिए अपने खुद के "की तरह बटन बनाने के लिए नहीं कर रहा हूँ "मेरी साइट के लिए। कोई विचार/सुझाव?

उत्तर

24

मैं आपको एक उदाहरण दूंगा। आप बस इससे सीखते हैं और तदनुसार परिवर्तन करते हैं।

myapp.models.py (सरलीकृत कंपनी मॉडल):

from django.db import models 
from django.contrib.auth.models import User 
from django.template.defaultfilters import slugify 


class Company(models.Model): 
    name = models.CharField(max_length=255) 
    slug = models.SlugField() 
    likes = models.ManyToManyField(User, related_name='likes') 

    @property 
    def total_likes(self): 
     """ 
     Likes for the company 
     :return: Integer: Likes for the company 
     """ 
     return self.likes.count() 

    def save(self, *args, **kwargs): 
     self.slug = slugify(self.name) 
     super(Company, self).save(*args, **kwargs) 

myapp.urls.py (एक दृश्य के लिए यूआरएल):

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

myapp.views। पीई (देखें):

from django.http import HttpResponse 
try: 
    from django.utils import simplejson as json 
except ImportError: 
    import json 
from django.shortcuts import get_object_or_404 
from django.contrib.auth.decorators import login_required 
from django.views.decorators.http import require_POST 

from myapp.models import Company 


@login_required 
@require_POST 
def like(request): 
    if request.method == 'POST': 
     user = request.user 
     slug = request.POST.get('slug', None) 
     company = get_object_or_404(Company, slug=slug) 

     if company.likes.filter(id=user.id).exists(): 
      # user has already liked this company 
      # remove like/user 
      company.likes.remove(user) 
      message = 'You disliked this' 
     else: 
      # add a new like for a company 
      company.likes.add(user) 
      message = 'You liked this' 

    ctx = {'likes_count': company.total_likes, 'message': message} 
    # use mimetype instead of content_type if django < 5 
    return HttpResponse(json.dumps(ctx), content_type='application/json') 

टेम्पलेट: इस {% url like %}

  • तरह URL नाम के आसपास उद्धरण चिह्नों के बिना

    • तो Django < 1.3 उपयोग url टैग तो Django > 1.3 and < 1.5 तो आप जोड़ना चाहिए:

      <input type="button" id="like" name="{{ company_slug }}" value="Like" /> 
      
      <script> 
      $('#like').click(function(){ 
           $.ajax({ 
             type: "POST", 
             url: "{% url 'like' %}", 
             data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'}, 
             dataType: "json", 
             success: function(response) { 
               alert(response.message); 
               alert('Company likes count is now ' + response.likes_count); 
             }, 
             error: function(rs, e) { 
               alert(rs.responseText); 
             } 
            }); 
          }) 
      </script> 
      

      url टैग टेम्प्लेट में उपयोग करने के लिए कुछ निर्देश {% load url from future %} at top level of your template and enclosed your URL name with quotes as I have done in my answer

    • यदि Django >= 1.5 तो बसहटाएं 10 और उद्धरण के रूप में {% load url from future %} रूप से बहिष्कृत कर दिया करने के लिए चिह्नित किया गया है और में Django 1.9
  • +1

    साथ ही, पेज लोड होने पर मैं पसंद की कुल संख्या या "आपको यह पसंद" कैसे प्रदर्शित करूंगा। क्या मुझे AJAX प्रकार प्राप्त करने की आवश्यकता है? – jmitchel3

    +0

    क्या आपको किसी ऑब्जेक्ट द्वारा पसंद की गई, बनाई गई = Like.objects.create (company = company) की वजह से 'ऑब्जेक्ट इज़ेरिएबल' त्रुटि नहीं मिल रही है? मैं वही काम करने की कोशिश कर रहा हूं लेकिन मुझे यह त्रुटि मिली है – Algorithmatic

    +0

    'कंपनी' मॉडल स्लग फ़ील्ड है ..? मुझे यह त्रुटि मिल रही है 'फ़ील्ड में कीवर्ड' स्लग 'को हल नहीं कर सकता। विकल्प हैं: सामग्री, निर्माण_डेट, आईडी, जैसे, शीर्षक, उपयोगकर्ता, user_id' –

    7

    यहाँ इस लेखन के बाद से मैं टिप्पणी करने के लिए पर्याप्त प्रतिष्ठा नहीं है और संपादन में कम से कम 6 अक्षर होना है हटा दिया जाएगा के साथ संलग्न URL नाम। Django के नए संस्करणों में, आपको स्ट्रिंग के रूप में यूआरएल टेम्पलेट टैग पर दृश्य फ़ंक्शन या यूआरएल का नाम पारित करने की आवश्यकता है। इसलिए ऊपर टेम्पलेट की लाइन 7 होगा:

    url: "{% url 'like' %}", 
    

    यहाँ documentation की बात यह है कि इस बैक अप ले लेता है।