问题描述
所以这不可能太难了,但我无法想像出来...
So this can't be too hard but I can't figure it out...
我想要我的表单在django(位于 / file_upload / )上传文件,将其添加到数据库,然后重定向到新页面,其中参数是我在数据库中添加的字段的ID(位于 /文件/ 163 / ,说)
I want my form in django (located at /file_upload/) to upload a file, add it to the database, and then redirect to a new page where the parameter is the id of the field that I've added in the database (located at /file/163/, say).
我已经设置了urls.py,以便 / file / 163 / 如果您直接在那里导航,但是我不知道如何从 / file / upload / 进入。
I've set up urls.py so that /file/163/ works just fine if you navigate there directly, but I don't know how to get there from /file/upload/.
我的代码就像这个:
def add(request):
if request.method == 'POST': # If the form has been submitted...
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
# do stuff & add to database
my_file = FileField.objects.create()
return HttpResponseRedirect(reverse('/file/', args=[my_file.id]))
我无法使用因为我在view.py中处理窗体之前不知道字段id是什么,所以重定向必须在views.py中发生。我想。
I can't use this solution because I don't know what the field id is going to be until I've handled the form in views.py, so the redirect has to happen in views.py. I think.
任何想法?
推荐答案
表单应该是这样的:
def add(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
# do stuff & add to database
my_file = FileField.objects.create()
# use my_file.pk or whatever attribute of FileField your id is based on
return HttpResponseRedirect('/files/%i/' % my_file.pk)
else:
form = UploadFileForm()
return render_to_response('upload_file.html', {
'form': form,
})
这篇关于Django使用HttpResponseRedirect形式重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!