单击下一步按钮时,如何使用相同的search_key更改此div?

时间:2016-01-16 03:07:13

标签: python django django-models jinja2

这是从instagram检索6个图像网址的views.py。第一次一切正常但是当我点击下一个按钮时,如何更改home.html文件中显示的6个图像(即检索6个新图像)?

def home(request):
    trends  = []
    if request.method == 'POST':  
        if request.POST.get('q'):
            search_key = request.POST.get('q').replace(" ","") 
            getImageFromInstagram(search_key)
        else:
            search_key = ''
        veriler = hashTags.objects.values_list('hashTag',flat=True)
        line = hashTags(hashTag=search_key,trends=search_key,image_url=tagUrl)
        line.save()
        return render(request, "home.html", {'trends':trends,'urls':urls,'hashtags':veriler})

def getImageFromInstagram():
    tagUrl = 'https://api.instagram.com/v1/tags/'+ search_key +'/media/recent?client_id=Hidden for security'
    q = requests.get(tagUrl).json()
    urls = [ q['data'][i]['images']['standard_resolution']['url'] for i in range(6)] 
    return urls   

结束home.html

<div class="col-md-8 timeline">
    {%for image_url in urls%} 
       <img src="{{image_url}}">
    {% endfor%}
</div>
<button type="submit" name="submit" class="btn btn-primary btn-lg btn-block">Next</button>

1 个答案:

答案 0 :(得分:0)

你的表格

<form action="{% url 'home' %}?next_url={{ next_url }}">
   <div class="col-md-8 timeline">
   <input name="q" type="text">
   {%for image_url in urls %} 
      <img src="{{image_url}}">
   {% endfor%}
   </div>
   <button type="submit" class="btn btn-primary btn-lg btn-block">Next</button>
</form>

你的views.py

def home(request):
    trends  = []
    if request.method == 'GET':  
        q = request.GET.get('q', '').replace(" ","") 
        next_url = request.GET.get('next_url', None)
        urls, next_url = getImageFromInstagram(q=q, next_url=next_url)
        # .. your other code
        return render(request, "home.html", {
             'trends': trends,
             'urls': urls, 
             'next_url': next_url,
        })

def getImageFromInstagram(q="", next_url=None):
    if next_url is not None:
        res = requests.get(next_url).json()
        urls = [ res['data'][i]['images']['standard_resolution']['url'] for i in range(6)]                   
    else:    
        tagUrl = 'https://api.instagram.com/v1/tags/'+ q+'/media/recent?client_id=Hidden for security'
        res = requests.get(tagUrl).json()
        urls = [ res['data'][i]['images']['standard_resolution']['url'] for i in range(6)] 

    next_url = res['pagination']['next_url']
    return urls, next_url

但我没有测试它。