如何从链接传递主键?Django模板遇No Reverse Found错误求解决
我来帮你一步步解决这个问题——核心就是URL反转时没正确传递主键,再加上User和UserProfile的一对一关联需要注意上下文传递,咱们逐个击破:
第一步:先确认你的URL配置是否正确
反转报错的头号原因,就是URL定义没包含主键参数,或者名称写错了。比如你的编辑资料视图,URL应该这样写(假设用UserProfile的主键):
# urls.py from django.urls import path from .views import NewUserProfileView, EditUserProfileView urlpatterns = [ path('profile/', NewUserProfileView.as_view(), name='user_profile'), # 这里<int:pk>就是要传递的主键参数,name要和模板里的反转名称一致 path('profile/edit/<int:pk>/', EditUserProfileView.as_view(), name='edit_profile'), ]
第二步:在你的FormView里传递UserProfile实例到模板
因为你用的是FormView,它默认不会自动把当前用户的UserProfile传到模板上下文,所以得重写get_context_data方法:
# views.py from django.views.generic import FormView, UpdateView from .models import UserProfile from .forms import UserProfileForm # 假设你已经定义了这个表单 class NewUserProfileView(FormView): template_name = "visit/user_profile.html" form_class = UserProfileForm def get_context_data(self, **kwargs): # 先调用父类方法获取默认上下文 context = super().get_context_data(**kwargs) # 把当前用户关联的UserProfile实例加到上下文里 context['user_profile'] = self.request.user.userprofile return context
第三步:在模板里调用主键并传递给URL反转
现在模板里就能拿到user_profile变量了,直接用它的pk参数生成编辑链接:
<!-- visit/user_profile.html --> <h2>我的个人资料</h2> <!-- 先展示一些资料信息示例 --> <p>用户名:{{ user.username }}</p> <p>昵称:{{ user_profile.nickname }}</p> <!-- 重点:生成编辑链接,传递主键 --> <a href="{% url 'edit_profile' pk=user_profile.pk %}">编辑我的资料</a>
额外排查:如果还是报No Reverse Found?
- 检查URL名称拼写:确保模板里的
{% url 'edit_profile' %}和urls.py里的name='edit_profile'完全一致,大小写、拼写都不能错。 - 确认编辑视图能接收主键:比如你的
EditUserProfileView如果是UpdateView,要指定model=UserProfile,这样它会自动用pk参数获取实例:class EditUserProfileView(UpdateView): model = UserProfile form_class = UserProfileForm template_name = "visit/edit_profile.html" success_url = "/profile/" # 编辑成功后跳回资料页 - 如果用User的主键代替UserProfile的:那URL里可以写成
<int:user_id>,模板里传pk=user.pk,编辑视图里通过User.objects.get(pk=self.kwargs['user_id']).userprofile获取实例就行。
补充:从其他页面传递主键的通用方法
比如在用户列表页要生成编辑链接,直接遍历实例传递pk即可:
{% for profile in all_profiles %} <a href="{% url 'edit_profile' pk=profile.pk %}">编辑{{ profile.user.username }}的资料</a> {% endfor %}
内容的提问来源于stack exchange,提问作者Sidharth Singh
相关产品推荐
相关产品推荐

