【问题标题】:Django render dictionary object in template through ajax getDjango通过ajax get在模板中渲染字典对象
【发布时间】:2014-04-19 18:55:01
【问题描述】:

嘿,伙计们,我想弄清楚如何通过 ajax 执行 GET 请求以返回一个字典对象,我可以使用 Django 的模板标签来迭代并显示结果。我似乎无法弄清楚这一点。任何帮助是极大的赞赏。谢谢。

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>

查看:

@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})

更新:::添加模型。

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  

【问题讨论】:

    标签: jquery python ajax django dictionary


    【解决方案1】:

    你需要返回一个json对象让jQuery理解。

    试试这个:

    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)
    

    【讨论】:

    • 不幸的是,这给了我一个内部服务器错误。如果我能够返回 json 对象,如何通过模板标签对其进行迭代?或者,这不可能吗?
    • 我发现我做错了什么,我忘了导入model_to_dict。这行得通。我知道我需要某种 for 循环来处理 json 数据。我要迭代什么?
    • 这将是一个 json 对象的简单迭代。示例:stackoverflow.com/questions/800593/…
    • 谢谢。我想我的意思是你将如何引用 json 对象?对不起,如果这是一个愚蠢的问题。类似 """result.topic_list[i].topic"""?
    • 实际上,console.log 应该准确地显示 json 对象的结构。弄清楚如何对其进行迭代应该很简单。
    猜你喜欢
    • 2020-08-10
    • 2012-01-11
    • 1970-01-01
    • 2014-05-12
    • 2021-04-11
    • 2018-09-29
    • 2014-08-25
    • 1970-01-01
    • 2018-11-25
    相关资源
    最近更新 更多