1

Hey guys i am trying to figure out how to do a GET request through ajax to return a dictionary object that I can use Django's template tags to iterate through and show the results. I can't seem to figure this out. Any Help is GREATLY appreciated. Thanks.

Ajax/html:

        $("#{{fabCatagory.categoryId}}btn").click(function(){

              $.ajax({

                       type: 'GET',
                       url: '/companion/topic/{{fabCatagory}}/',

                       success: function(result){
                       console.log(result['topics'])
                       },
                     });
                    });





    <div id="{{fabCatagory.categoryId}}" class="panel-collapse collapse">
       <div class="panel-body">

         <div class="list-group">
            {%for fabCatagory in topics %}

               <a id="{{ fabCatagory.topicId }}" class="list-group-item">{{ fabCatagory.topic }}</a>

            {% endfor %}
        </div>
     </div>
   </div>

View:

@render_to ('companion/companionSub.html')
def topic(request, id):   

    ids = Catagories.objects.get(catagory=id)
    topics = Topics.objects.filter(fabCatagory_id=ids.id).all()
    topic_list = {'topics':topics}
    return HttpResponse({'topics':topics})

Update:::Adding Models.

from django.db import models
from embed_video.fields import EmbedVideoField
from imagekit.models import ProcessedImageField
from imagekit.processors import ResizeToFill

class Catagories(models.Model):
   catagory = models.CharField(max_length=128)
   categoryId = models.CharField(max_length=128)
   def __unicode__(self):
    return self.catagory 

class Topics(models.Model):
   fabCatagory = models.ForeignKey(Catagories)
   topic = models.CharField(max_length=128)
   topicId = models.CharField(max_length=128)
   def __unicode__(self):
    return self.topic 

class Fabrics(models.Model):
   fabTopic = models.ForeignKey(Topics)
   fabName = models.CharField(max_length=128)
   fabContent = models.CharField(max_length=128, blank=True)
   fabWeave = models.CharField(max_length=128, blank=True)
   fabDye = models.CharField(max_length=128, blank=True)
   fabFinish = models.CharField(max_length=128, blank=True)
   fabDescription = models.CharField(max_length=8192) 
   fabImage = ProcessedImageField(upload_to='avatars',
                                       processors=[ResizeToFill(250, 185)],
                                       format='JPEG',
                                       options={'quality': 60},blank=True) 
   fabImage_secondary = ProcessedImageField(upload_to='avatars',
                                       processors=[ResizeToFill(500, 370)],
                                       format='JPEG',
                                       options={'quality': 60},blank=True)
   fabVideo = EmbedVideoField(blank=True)
   fabVideoURL = models.URLField(blank=True)
   isPremium = models.BooleanField(default=False)
   def __unicode__(self):
    return self.fabName  
pdf2e
  • 177
  • 1
  • 3
  • 16

1 Answers1

2

You need to return a json object for jQuery to understand.

Try this:

import json
from django.forms.models import model_to_dict

@render_to ('companion/companionSub.html')
def topic(request, id):   

    ids = Catagories.objects.get(catagory=id)

    topics = [model_to_dict(topic) for topic in Topics.objects.filter(fabCatagory_id=ids.id)]
    topic_list = json.dumps({'topics':topics})

    return HttpResponse(topics_list)
karthikr
  • 97,368
  • 26
  • 197
  • 188
  • Unfortunately, this is giving me an internal server error. If I am able to return the json object, how can I iterate through it via template tags? Or, is this not possible. – pdf2e Apr 19 '14 at 19:56
  • I figured out what I had done wrong, I forgot to import model_to_dict. This worked. I understand that I will need a for loop of some kind to process the json data. What to I iterate over? – pdf2e Apr 19 '14 at 21:49
  • That would be a simple iteration of a json object. Example: http://stackoverflow.com/questions/800593/loop-through-json-object-list – karthikr Apr 19 '14 at 21:51
  • Thank you. I guess I mean how would you reference the json object? Sorry if this is a stupid question. Something like """result.topic_list[i].topic"""? – pdf2e Apr 19 '14 at 22:00
  • actually, the console.log should show you exactly how the json object is structured. It should be simple to figure out how to iterate over the same. – karthikr Apr 19 '14 at 22:03
  • Nevermind, I got what you mean. I wish I could upvote you again. Thanks – pdf2e Apr 19 '14 at 22:25