【问题标题】:Django - Passing image objects to a second view for processing and db savingDjango - 将图像对象传递到第二个视图以进行处理和数据库保存
【发布时间】:2025-12-07 09:30:01
【问题描述】:

这是用例:

我的主页有一个图片上传表单。提交表单后,页面会加载一个 4x4 网格的上传图像,并应用不同的照片过滤器。单击一个选项会将经过所选处理的图像保存到数据库中。

我的问题是,在选择处理之前,我将如何在不保存到数据库的情况下执行此操作?

我不反对用这个问题来学习ajax。

【问题讨论】:

  • 如果用户离开网格页面,他们是否能够返回并完成选择?您是否有不想将原始图像保存到数据库然后用所选选择覆盖它的原因?
  • 您将不得不在请求之间以某种方式保存图像。如果不是数据库,那么是文件系统。 HTTP 是无状态的;如果没有一些存储后端,您将无法在视图之间传递这样的信息。

标签: django django-forms django-views


【解决方案1】:

在一个视图中执行;它必须考虑三种可能性:

  • 用户刚刚到达页面 - 为他们提供一个空表单 (InitialImageForm)
  • 用户提交了一张图片 - 不要保存它,而是创建 4 张新图片并使用新表单 (ProcessedImageForm) 将它们传回,允许他们选择其中一张生成的图片
  • 用户现在已经提交了最终表单以及原始图像和选择的处理图像 - 全部保存

这段代码有点乱,但它给了你想法。您需要自己编写两个表单,可能还有一个模型来表示图像和处理/选择的图像

from PIL import Image
def view(self, request):
    if request.method=='POST':
        # We check whether the user has just submitted the initial image, or is
        # on the next step i.e. chosen a processed image.
        # 'is_processing_form' is a hidden field we place in the form to differentiate it
        if request.POST.get('is_processing_form', False): 
            form = ProcessedImageForm(request.POST)
            if form.is_valid():
                # If you use a model form, simply save the model. Alternatively you would have to get the data from the form and save the images yourself. 
                form.save()
                return HttpResponseRedirect('/confirmation/')
        elif form.POST.get('is_initial_form', False) and form.is_valid():
            form = InitialImageForm(request.POST)
            if form.is_valid():
                # Get the image (it's not saved yet)
                image = Image.open(form.cleaned_data.get('image').url)
                processed_list = []
                # Create your 4 new images and save them in list
                ...
                # You can show a template here that displays the 4 choices
                return direct_to_template(request,template =  'pick_processing.html',extra_context = { 'image' : image, 'processed_list':processed_list })
    else:
        # When the user arrives at the page, we give them a form to fill out
        form = ImageSubmitForm()
    return direct_to_template(request,template = 'upload_image.html',extra_context = { 'form' : form })

【讨论】:

    最近更新 更多