问题
I have an Image Gallery System where I'm building a feature to edit the attributes of an uploaded image.
@login_required
def edit(request):
if request.method == 'POST':
ZSN = request.POST['ZSN']
ZSN = 'images/' + ZSN + '.'
image = Images.objects.filter(file__startswith=ZSN)
if image:
return HttpResponseRedirect('/home/photo-edit', {'image':image})
else:
return HttpResponse("Invalid ZSN.")
else:
return render(request, 'cms/edit.html')
This is my edit
method in views.py
. Notice that I am getting the image
object as the image whose attributes has to be edited. If the image is found then I'm redirecting to home/photo-edit where I want to display a HTML page containing a form with image attributes, pre-filled with existing attributes.
My views.py method for home/photo-edit/ URL is
@login_required
def photoedit(request):
return render(request, 'cms/photo-edit.html', {'image':image})
But image here isn't getting recognised even though I am sending it from home/edit
to home/photo-edit
. How do I do this? Is he syntax wrong?
回答1:
You could solve this be passing the ZSN
or the Image
PK as an URL parameter to the next view. You need to do that because the actual Image
instance can not be passed to the next view directly.
For example:
urls.py
from . import views
urlpatterns = [
url(r'^home/edit/$', views.edit, name='edit'),
url(r'^home/photo-edit/(?P<photo_id>[0-9]+)/$', views.photo_edit, name='photo-edit'),
]
views.py
def edit(request):
if request.method == 'POST':
...
image = Images.objects.filter(...).first()
if image is not None:
return redirect('photo-edit', image.pk)
else:
return HttpResponse("Invalid ZSN.")
else:
return render(request, 'cms/edit.html')
def photo_edit(request, image_pk):
image = get_object_or_404(Image, pk=image_pk)
...
Note how in this example the line redirect('photo-edit', image.pk)
passes the image PK to the next view.
Now you would just need to implement the view photo_edit
to fit your use case.
Let us know if that brings you closer to solving your problem.
来源:https://stackoverflow.com/questions/51516510/passing-information-between-web-pages-in-django