django - 如何使用基于 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 获取“用户名”,这样做不允许我获得更新特定用户名所需的表单。
任何帮助都会很棒。谢谢。
解决方案
在您EditProfileViewClass
看来,您可以添加pk_url_kwarg
或slug_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'
推荐阅读
- graphql - 用户表,其中用户在 Amplify 中关注其他用户
- c++ - 如何过滤/区分由 Windows API NotifyIpInterfaceChange() 捕获的实际事件和“虚拟”事件
- ios - 来自 UserDefault 的类型转换值会引发错误
- python - /students/delete_gr/234/ 的字段错误
- spring-boot - 如何更新在 docker 容器中运行的应用程序?(例如,弹簧靴)
- java - Spring AOP 记录器跟踪 ID 与 Spring Cloud Sleuth?
- python - 当 unix 服务器使用 VShell 时使用 paramiko
- prometheus - 呼叫警报与 Prometheus Alertmanager 集成
- angular -
不是已知元素。请确认它是此模块的一部分 - node.js - Sails:在单个服务器中使用不同的项目