【问题标题】:NoReverseMatch error when loading profile detail page加载配置文件详细信息页面时出现 NoReverseMatch 错误
【发布时间】:2021-05-01 13:34:13
【问题描述】:

我正在尝试加载一个模板来查看我的自定义 UserEntry 配置文件的详细信息。当我转到应该加载基于类的视图的 URL 时,我从 Django 收到此错误:

Reverse for 'UserProfile' with arguments '('',)' not found. 1 pattern(s) tried: ['user/profile/(?P<pk>[0-9]+)/$']

views.py:

class UserProfileView(DetailView):
    model = UserEntry
    template_name = 'userprofile_app/userprofile.html'

    def get_context_data(self, *args, **kwargs):
        users = UserEntry.objects.all()
        context = super(UserProfileView, self).get_context_data(*args, **kwargs)     
        page_user = get_object_or_404(UserEntry, id=self.kwargs['pk'])
        context['page_user'] = page_user
        return context

urls.py:

urlpatterns = [
    path('entry/', UserRegistrationView.as_view(), name='UserEntry'),
    path('profile/<int:pk>/', UserProfileView.as_view(), name='UserProfile'),
]

模板:

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <a class="navbar-brand" href="{% url 'UserProfile' UserEntry.id %}">EDIT PROFILE</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

模型.py

class UserEntry(models.Model):
   id = models.AutoField(primary_key=True, unique=True)
   name = models.CharField(max_length=264)

【问题讨论】:

    标签: django django-views django-templates django-urls


    【解决方案1】:

    问题是 UserEntry.id 是空的,这就是它抛出错误的原因。确保您将正确的 UserEntry 对象传递到模板中

    【讨论】:

    • 我可以看看你的 UserEntry 模型吗?
    • 您是否将 UserEntry 对象传递到您的模板中?
    • 网址未获取 UserEntry.id。
    • UserEntry对象应该如何传递
    • 哪个视图呈现您提到的模板?
    【解决方案2】:

    您需要将用户 ID 分配给您在 urls.py 中使用的变量名称(pk)

    pk = page_user.id

    <a class="navbar-brand" href="{% url 'UserProfile' pk=page_user.id %}">EDIT PROFILE</a>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多