【发布时间】:2022-01-09 15:40:08
【问题描述】:
我想更改从模板发送到更新视图的主键。让我解释。这是我的模板:
<a href="{% url 'new_url' model_instance.pk %}">
{{ model_instance.username }}
</a>
此model_instance 是列表视图中上下文变量model_instances 的for 循环中的一个实例。 model_instance 的这个主键随后将被发送到以下视图:
class UserUpdateView(generic.UpdateView):
template_name = "leads/update.html"
queryset = User.objects.all()
context_object_name = "user"
form_class = UserUpdateForm
def get_success_url(self):
return reverse("some-url")
但是,问题是我发送给UserUpdateView 的主键是model_instance 模型的主键,而不是User 模型的主键。此外,两个模型之间没有像一对一关系那样的链接。但是,有相似之处。 model_instance 和 user 都有一个相同的 username 字段。
换句话说,我需要先检索model_instance.username,然后查询User 模型以找到与我要更新的相同username 的user 实例。目前,UserUpdateView 只是接收模板中model_instance 的主键,这不是我想要的。我希望你们能帮助我解决这个问题,并请留下您的任何问题。谢谢。
【问题讨论】:
标签: django django-models django-views django-forms django-templates