嗨,如何使用 Django 将照片添加到网页?

Hi,How can I add a photo to a web page with Django?

提问人:zahra shokrizadeh 提问时间:7/22/2023 更新时间:7/22/2023 访问量:31

问:

如何创建此功能,以便用户可以从系统内为产品选择照片或输入其 URL?此图像应与其他信息一起添加到产品列表中。

这是我的代码。页面加载,但它没有做任何特别的事情,也没有 URL 框。

{% extends "auctions/layout.html" %}

{% block body %}
    <h2 id="h2">Create List</h2>

    <form method="POST">
        {% csrf_token %}
        <h3 id="h3">Title:</h3>
        <input id="input" placeholder="Title" type="text" name="createlist_title"/>

        <h3 id="h3">Category:</h3>
        <input id="input" placeholder="Category" type="text" name="category"/>
        
        <h3 id="h3">Description:</h3>
        <textarea id="input" placeholder="Description"  type="text" name="createlist_description">
        </textarea>
        
        <h3 id="h3">Firstprice:</h3>
        <input id="input" placeholder="first_price" type="number" name="createlist_price"/>
        
        <form action="upload.php" method="post" enctype="multipart/form-data">
            <h3 id="h3"> Upload image:</h3>
            <input id="input" type="file" id="fileUpload" name="fileUpload">
            <input id="button2" type="submit" value="upload">
        </form>``

        <form method="post" enctype="multipart/form-data" action="{%url "upload_image" %}">
            <h3 id="h3"> Upload image with URL:</h3>
            {% csrf_token %}
            {{ form.as_p }}
            <button id="button2" type="submit">Upload</button>
        </form>
            
        <button id="button" class="btn btn-outline-primary" type="submit">Submit</button>
        
    </form>
HTML 图像 形式 django-models

评论

0赞 Rob 7/22/2023
不是修复,但请注意,<input> 标记不使用也不需要右斜杠,并且在任何 HTML 规范中都没有。

答:

0赞 Kiarash Gh 7/22/2023 #1

根据您的模板,“models.py”文件应如下所示:

from django.db import models

class Product(models.Model):
    title = models.CharField(max_length=100)
    category = models.CharField(max_length=50)
    description = models.TextField()
    first_price = models.DecimalField(max_digits=10, decimal_places=2)
    image = models.ImageField(upload_to='product_images/', null=True, blank=True)

    def __str__(self) -> str:
        return self.title

您可以使用“forms.py”来创建产品并上传图像,为此,首先创建一个名为“forms.py”的文件,其中“models.py”,并在该文件中:

from django import forms

class ProductForm(forms.Form):
    title = forms.CharField(max_length=100)
    category = forms.CharField(max_length=50)
    description = forms.CharField(widget=forms.Textarea)
    first_price = forms.DecimalField(max_digits=10, decimal_places=2)
    image_upload = forms.ImageField(required=False)  # For local file upload
    image_url = forms.URLField(required=False)  # For URL-based image upload

那么你的“views.py”文件应该是这样的:

from django.shortcuts import render, redirect
from .forms import ProductForm
from .models import Product

def create_product(request):
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)
        if form.is_valid():
            title = form.cleaned_data['title']
            category = form.cleaned_data['category']
            description = form.cleaned_data['description']
            first_price = form.cleaned_data['first_price']
            image_upload = form.cleaned_data['image_upload']
            image_url = form.cleaned_data['image_url']

            product = Product(
                title=title,
                category=category,
                description=description,
                first_price=first_price,
            )

            if image_upload:
                product.image = image_upload
            elif image_url:
                product.image = image_url

            product.save()

            # you can redirect to the product list or detail page like this:
            # return redirect('product_list') 

    else:
        form = ProductForm()

    return render(request, 'upload/create_product.html', {'form': form}) # I have named the app "upload" you should use your own app name

“create_product.html”文件应该是这样的:

{% extends "auctions/layout.html" %}
{% block body %}
    <h2 id="h2">Create List</h2>

    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button id="button" class="btn btn-outline-primary" type="submit">Submit</button>
    </form>
{% endblock %}

为了处理图像,您应该安装“枕头”库:

pip install Pillow

最后,您应该将其添加到“settings.py”文件中以保存图像:

import os
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

我希望这对你有所帮助。

评论

0赞 zahra 7/23/2023
谢谢。我能够解决我的问题。祝你好运
0赞 Kiarash Gh 7/24/2023
祝你好运:)