在Django中的网页之间传递信息 [英] Passing information between web pages in Django

查看:162
本文介绍了在Django中的网页之间传递信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图片库系统,其中正在构建一个功能来编辑上载图像的属性。

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')

这是我的编辑 views.py 中的c>方法。请注意,我得到 image 对象作为其属性必须编辑的图像。如果找到了图像,那么我将重定向到首页/照片编辑,在这里我要显示一个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.

我的home / photo-edit / URL的views.py方法是

My views.py method for home/photo-edit/ URL is

@login_required
def photoedit(request):
    return render(request, 'cms/photo-edit.html', {'image':image})

但是即使我是从 home / edit 家庭/照片编辑。我该怎么做呢?他的语法错误吗?

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?

推荐答案

您可以通过传递 ZSN 或图片 PK作为下一个视图的URL参数。您需要这样做,因为实际的 Image 实例不能直接传递到下一个视图。

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.

例如:

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)
    ...

请注意在此示例中 redirect('photo-edit ',image.pk)将图像PK传递到下一个视图。
现在您只需要实现视图 photo_edit 来适应您的用例。

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.

这篇关于在Django中的网页之间传递信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆