我有一个用于作业的博客项目,除了用户配置文件编辑和删除之外,我拥有所有功能。
我已经创建了个人资料页面并能够编辑该页面。当我提交更新请求时,我可以看到它提交了更改,因为在我收到错误后,个人资料页面已更新。
我收到此错误,我知道这是由于重定向造成的,但我一生都无法弄清楚如何重定向回用户配置文件。我尝试只使用 httpredirect 或反向,现在使用reverse_lazy,因为这对于博客文章、评论和编辑来说效果很好。
这是我的错误和代码如下。 我相信这取决于 get_success_url,并希望有人遇到过此错误或知道对此的最佳解决方案。谢谢你
/1/edit_profile_page/ 处无反向匹配 与“show_profile_page”相反,没有找到参数。尝试了 1 个模式:['(?P[0-9]+)/profile/\Z']
视图.py
class EditProfile(LoginRequiredMixin,
SuccessMessageMixin,
UserPassesTestMixin,
generic.UpdateView):
model = Profile
template_name = 'edit_profile_page.html'
form_class = ProfileForm
success_message = 'Updated Profile'
def get_success_url(self):
return reverse_lazy('show_profile_page')
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
def test_func(self):
profile = self.get_object()
if self.request.user == profile.user:
return True
return False
URLS.PY
urlpatterns = [
path('<int:pk>/profile/', ShowProfilePageView.as_view(),
name="show_profile_page"),
path('<int:pk>/edit_profile_page/', EditProfile.as_view(),
name='edit_profile_page'),
]
表格.PY
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = [
'bio',
'country',
]
widgets = {
'bio': SummernoteWidget(),
'country': CountrySelectWidget(),
}
我期待提交表格后重定向到主页。个人资料页面使用
websiteurl/id/profile
作为查看个人资料的路径。我认为使用reverse_lazy提交表单后重定向到ShowProfilePageView,但我似乎找不到它的工作原理并且遇到了障碍。
show_profile_page
的 url 模式需要一个 id 作为您未传递的参数:
path('<int:pk>/profile/', ShowProfilePageView.as_view(),
name="show_profile_page")
像这样传递:
def get_success_url(self):
return reverse_lazy('show_profile_page', kwargs={'id': self.id})