0

我正在尝试使用 shell 初始化一个图像文件,该文件已经存在于我的系统上。但这会创建该文件的副本并将其存储在指定位置。我想要的是应该使用的文件和不应该创建它的副本。另外,我希望将该图像发送到我的“base.html”文件以便下载(在对该图像执行任务之后)。这是我的模型和 shell 命令。

注意:所有进口都得到照顾。

表格.py

class MyForm(forms.ModelForm):
    class Meta:
        model = Manupulation
        fields = '__all__'

我的模型:

class Manupulation(models.Model):
    image = models.ImageField(upload_to='media',blank=True)
    new_image = models.ImageField(upload_to='media',blank=True)

外壳命令:

    from django.core.files import File
    from {my app name}.models import Manupulation
    item = Manupulation()
    item.image.save("<filename>", File(open("<File path>", "rb")))    # "rb" mode for python 3
    item.new_image.save("<filename>", File(open("<File path>", "rb")))

视图.py

def home(request):
    if request.method == "POST":
        form = MyForm(request.POST, request.FILES)
        ...
        ...
        if form.is_valid():
            data = form.save()
            # perform some actions on the uploaded file.
            # this creates a new file and now I want my model to have this file as a field(new_image field).

            item = Manupulation.objects.get(pk=data.id)
            item.new_image = <??> # somehow put that new image here
            # this new_image should contain the file which is generated by this view.
            return render(request, "base.html", {'Download_image': item}
    form = MyForm()
    return render(request, "base.html", "form": form)
        

索引.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Index Page</title>
</head>
<body>
    <form method="POST" action="{% url 'home' %}" enctype="multipart/form-data">
        {% csrf_token  %}
        {{form.as_p}}
        <button type="submit" >submit</button>
    </form>
    {% if Download_image %}
    <a href="{{ Download_image.new_image.url }}"  download >Download Image</a>
</body>
</html>

这将在我的媒体目录中创建一个文件(我不想要的那个图像的副本)。请有人帮我解决这个问题。

4

0 回答 0