试图使if语句起作用。

from __future__ import unicode_literals

from django.shortcuts import render

def index(request):
   return render(request, 'landscapes/index.html')

def landscape(request, id):
    print id
    if id>=1 and id<=10:
        print 'true'
        landscape = 'https://wildwithgrace.files.wordpress.com/2010/12/snowy-landscape.jpg'
    context = {
        'landscape': landscape
    }
    return render(request, 'landscapes/landscape.html', context)


即使数字大于1且小于10,也只会在/#处返回UnboundLocalError。

urls.py:

from django.conf.urls import url, include
from . import views

urlpatterns = [
    url(r'^$', views.index),
    url(r'^(?P<id>\d+)$', views.landscape),
]

最佳答案

def landscape(request, id):
    print id
    if int(id) >= 1 and int(id) <= 10:
        print 'true'
        landscape = 'https://wildwithgrace.files.wordpress.com/2010/12/snowy-landscape.jpg'
        context = {
            'landscape': landscape
        }
    else:
        context = {}
    return render(request, 'landscapes/landscape.html', context)


尝试这个

10-06 09:44