gpt4 book ai didi

python - 如何在 Django View 之间传递数据

转载 作者:太空狗 更新时间:2023-10-29 19:34:07 26 4
gpt4 key购买 nike

This问题一般解决我的问题,但我正在寻找更具体的解释。

我希望用户更新一组模型对象,但是,需要先检索这些对象的查询集。我的计划是在两个单独的 UR/ View 中执行此操作,从第一个获取查询集信息,然后显示接下来要更新的模型表单集。

我的第一个 View 给出了所有“项目”的列表(我的模型之一),并检索了所选项目的 ID。

这是表格:

class ProjectLookupForm(forms.Form):
Project_Name = chosenforms.ChosenModelChoiceField(queryset=Project.objects.all())

这是 View :

def update_project_filter(request):
project_form = ProjectLookupForm(request.POST or None)
if request.method == 'POST':
if project_form.is_valid():
context = {"project_form":project_form}
# Get project here and share it with the next view.
selected_project_id = project_form.cleaned_data["Project_Name"].id
# Add a new return statement here?
# Or call update project view from here?
# Add a redirect button to html?
else:
errors = project_form.errors
context = {"errors":errors, "project_form":project_form}
else:
context = {"project_form":project_form}
return render(request, 'filter_update_project_form.html', context)

如您所见,我已经包含了一些集思广益我的可能性的评论。我的目标是将 selected_project_id 发送到下一个 View ,以便它可以将该 id 用作模型表单查询集。

def update_project(request):
UpdateFormset = modelformset_factory(Sample, fields=("sample_name", "extraction_date",
"project", "order", "notebook", "notebook_page"))
if request.method == 'POST':
formset = UpdateFormset(request.POST, request.FILES)
if formset.is_valid():
formset.save()
context = {"formset": formset, "project_form":project_form}
else:
errors = formset.errors
context = {"formset":formset, "errors":errors, "project_form":project_form}
else:
formset = UpdateFormset(queryset=Sample.objects.filter(project=2))
context = {"formset":formset, "project_form":project_form}
return render(request, 'update_project_form.html', context)

在这里可以看到我已经像这样对查询集进行了硬编码:

queryset=Sample.objects.filter(project=2)

如何将“project=”设置为我的 selected_project_id?我是否将此信息作为输入参数传递给 View ?还是我将它发送到下一个 URL 并从那里获取?

最佳答案

假设您已激活 django.contrib.sessions.middleware.SessionMiddleware ;您可以使用 request.session 字典在 View 之间传递数据,如下所示:

def update_project_filter(request):
...
selected_project_id = project_form.cleaned_data["Project_Name"].id
request.session['selected_project_id'] = selected_project_id
...

def update_project(request):
...
selected_project_id = request.session.get('selected_project_id')
...

关于python - 如何在 Django View 之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32787838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com