get_object_or_404找不到错误页面

时间:2016-01-04 11:18:56

标签: python django python-2.7 django-models

我正试图在电话号码和消息之间建立一对多的关系。每当我选择一个数字来显示发送到该号码的消息时,我就会收到404错误。

views.py

def index(request):
    number = phoneNumber.objects.all()
    return render(request, 'index.html', {'number': number})

def detail(request, phonenumber):
    messages = get_list_or_404(Message, to=phonenumber)
    return render(request, 'messages.html', {'messages': messages})

models.py

class phoneNumber(models.Model):
    address = models.CharField(max_length=15)

    def __str__(self):
        return self.address

class Message(models.Model):
    to = models.ForeignKey(phoneNumber)
    sentfrom = models.CharField(max_length=15)
    content = models.TextField()

    def __str__(self):
        return '%s' % (self.content)

urls.py

urlpatterns = [
        url(r'^$', views.index, name='index'),
        url(r'(?P<phonenumber>[0-9]+)', views.detail, name='detail'),
 ]

的index.html

{% for num in number %}
    <ul>
        <li><a href="{% url 'detail' phonenumber=num.address %}">{{ num.address }}</a></li>
    </ul>
{% endfor %}

messages.html

{% for message in messages %}
    <p>{{ message }}</p>
{% endfor %}  

1 个答案:

答案 0 :(得分:2)

您需要先捕获电话号码对象,然后才能进行过滤。

def detail(request, phonenumber):
    phonenumber_obj = get_object_or_404(phoneNumber, address=phonenumber)
    messages = get_list_or_404(Message, to=phonenumber_obj)
    return render(request, 'messages.html', {'messages': messages})