I don't know how to use Django's image input form.

Asked 2 years ago, Updated 2 years ago, 75 views

I was able to display the image input form on the web page, but I don't know how to use the image attached to the input form.I would like to retrieve the information in the image

#view.py
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from.models import Post

def index(request):
param={
        'form' —PhotoForm(),            

    }
if(request.method=='POST'):      
    params ['form'] = PhotoForm (request.POST, request.FILES)
return render (request, 'cp4/index.html', params)
 from django.db import models

# Create your models here.
class Post (models.Model):
title=models.CharField(max_length=100)
image=models.ImageField(upload_to='media/')

def__str__(self):
    return self.title
 from django import forms                                                           

class PhotoForm (forms.Form):
form = forms.ImageField()
<form action="{%url'index'%}" method="post" enctype="multipart/form-data" id="upload_form">
    {% csrf_token%}
    {{ form}}
    <input type="submit" value="click">
</form>

python django

2022-09-30 16:06

1 Answers

For Django 2, the basic upload process is introduced on this page.

Django Documentation - Uploading Files

Here's how to handle the uploaded file:

default_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
・・・

A common way to handle an uploaded file is as follows:

def handle_uploaded_file(f):
    with open('some/file/name.txt', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

First, please read this page carefully.


2022-09-30 16:06

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.