首页 > 解决方案 > 如何使用基于 Django 函数的视图来更新模型?

问题描述

我使用基于类的视图来使用此代码更新用户配置文件

class EditProfileViewClass(generic.UpdateView):
    model = UserProfile
    fields = ['bio', 'profile pic']
    template_name = 'users/update.html'
    success_url = reverse_lazy('home')

path('profile/<int:pk>/update', EditProfileViewClass.as_view(), name="profile"),

<a href="{% url 'profile' user.id %}">Your Profile</a>

现在的问题是,我希望它像上面那样,而不是像上面那样

path('profile/<str:username>/update', EditProfileViewClass.as_view(), name="profile"),

但不幸的是,我收到一个属性错误说:

Generic detail view EditProfileView must be called with either an object pk or a slug in the URLconf.

所以我尝试制作一个基于函数的视图,以便我可以从 url 获取“用户名”,这样做不允许我获得更新特定用户名所需的表单。

任何帮助都会很棒。谢谢。

标签: djangodjango-views

解决方案


在您EditProfileViewClass看来,您可以添加pk_url_kwargslug_url_kwarg

class EditProfileViewClass(UpdateView):
    model = UserProfile
    fields = ['bio', 'profile pic']
    template_name = 'users/update.html'
    success_url = reverse_lazy('home')
    pk_url_kwarg = 'username'
    slug_url_kwarg = 'username'

推荐阅读