我通过来自其他地方的HttpResponseRedirect调用我的“editFamily”视图:
url(r'^editFamily/(?P<pk>[0-9]+)/$', views.editFamily, name='editFamily')
相应的网址格式如下所示:
def editFamily(request, pk_):
obj = models.Family.objects.all().filter(pk=pk_)
if request.method == 'POST':
form = forms.FamilyForm(request.POST, instance=obj)
if form.is_valid():
form.save()
else:
form = forms.FamilyForm(instance=obj)
return render(request, 'editFamily.html', {'form': form})
然后终于有了我的观点:
Option Explicit
Sub mySub()
dim WBaPath as String
dim WBbPath as String
WBaPath = "Y:\BI-Accounting\myWorkbook.xlsm"
WBbPath = "Z:\Portal\myOtherWorkbook.xlsm"
dim WBa as Workbook
dim WBb as Workbook
set WBa = Workbooks.open(WBaPath)
set WBb = ThisWorkbook
'Code to do stuff
End Sub
它需要pk_,最终在else分支中并提供我的edit-html。但是在观众提交关于参数pk_的数据之后会发生什么?我从POST来的时候pk_丢失了吗?我是否必须确保在我的模板中传递该参数?
答案 0 :(得分:2)
因为您想使用除pk之外的其他变量。为方便起见,请使用变量id
将urls.py更改为
url(r'^editFamily/(?P<id>[0-9]+)/$', views.editFamily, name='editFamily')
在views.py中,您可以从网址路径中访问变量
def editFamily(request, id):
obj = models.Family.objects.all().filter(pk=id)
if request.method == 'POST':
form = forms.FamilyForm(request.POST, instance=obj)
if form.is_valid():
form.save()
else:
form = forms.FamilyForm(instance=obj)
return render(request, 'editFamily.html', {'form': form})
在urls.py和views.py中使用相同的名称非常重要,以便view函数可以按名称从其url路径中选择变量。
答案 1 :(得分:1)
不,它不会丢失。表单提交到同一页面,因此URL保持不变,参数仍然存在。