首页 > 解决方案 > Python/Django URL

问题描述

免责声明.....这是一项任务!有人能告诉我为什么我会得到

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/%7B%20%25%20url%20'detail'%20user%20%25%20%7D
Using the URLconf defined in bobbdjango.urls, Django tried these URL patterns, in this order:

[name='home']
profile [name='profile']
user_detail/<str:user_id> [name='detail']
The current path, { % url 'detail' user % }, didn’t match any of these.

You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

我认为这是我的 URL 的问题,但我没有看到错误来源。我只想单击主页上的链接并转到用户详细信息页面。请参阅下面的代码...我的主页

<body>
    {% block content %}
    <h1>This is home page</h1>
    <div>
        <!-- <a href="{% url 'profile' %}">Your profile</a> -->
        {% for user in users %}
        <a href="{ % url 'detail' user % }">
        <h3>{{user.first_name}}</h3>
        </a> 
        {% endfor %}
       
    </div>
    {% endblock %}

</body>

我的主要网址

urlpatterns = [
  ## path('admin/', admin.site.urls),
    path('', include('bobbpets.urls') ),
  ##  path('bobbpets/<int:user.id/>', views.userDetails, name='userDetails'),
]

我的应用网址

urlpatterns = [
  ##  path('admin/', admin.site.urls),
    path('', views.home, name='home'),
   path('profile', views.profile, name='profile'),

    path('user_detail/<str:user_id>', views.userdetail, name='detail'),
]

我的观点

def home(request):
    users = User.objects.all()
    return render(request, 'home.html', {'users': users})

def userdetail(request,user_id):
    user = User.objects.get(id=user_id)
    return render(request, 'user_detail.html', {'user': user})

def profile(request):
    return render(request, 'profile.html')

我的模特

from django.db import models

class User(models.Model):
    first_name=models.CharField(max_length=30)
    last_name=models.CharField(max_length=30)
    email=models.EmailField()

    def __str__(self):
        return '{} {}'.format(self.first_name, self.last_name)

标签: pythondjangourl

解决方案


您的模板 URL 应如下所示:<a href="{% url 'detail' user %}

删除百分号和括号之间的空格。这将导致错误。


推荐阅读