你好,我如何在Django的网页上添加照片?

c2e8gylq  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(83)

如何创建此功能,以便用户可以从系统中选择产品的照片或输入其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>

字符串

waxmsbnn

waxmsbnn1#

根据您的模板,“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 %}


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

pip install Pillow


最后,你应该在你的“settings.py”文件中添加这个来保存图像:

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


我希望这对你有帮助。

相关问题