I'm making a web app using Django that requests images from users and processes them. When I use the following code:
<label for="imageFile">Upload a photo:</label>
<input type="file" id="imageFile" capture="user" accept="image/*">
I don't get an option to take a photo from the laptop's camera. Several websites said that the capture attribute might not work for desktop computers and I don't know what I should use instead.
This is my code
HTML:
{% extends "image/layout.html" %}
{% load static %}
{% block body %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="image" accept="image/*" capture="user">
<input type="submit" value="Upload">
</form>
{% endblock %}
Views.py:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .models import *
def index(request):
if request.method == 'POST':
img = request.POST['img']
#save image in model
return render(request, 'image/image.html')
else:
return render(request, 'image/image.html')
I haven't implemented the procedure to save the image yet.
CodePudding user response:
You may use the following:
<form method="post" enctype="multipart/form-data">
<input type="file" name="image" accept="image/*" capture="user">
<input type="submit" value="Upload">
</form>
CodePudding user response:
create forms.py inside your app.
forms.py
from django import forms
class ImageForm(forms.Form):
image = forms.ImageField()
views.py
from .forms import ImageForm
from django.http import HttpResponseRedirect
from django.shortcuts import render,redirect
from .models import *
def index(request):
if request.method == 'POST':
form = ImageForm(request.POST,request.FILES)
if form.is_valid():
image = form.cleaned_data['image']
#save image in model
return redirect('index')
else:
form = ImageForm()
return render(request, 'image/image.html',{'form':form})
inside your urls.py
from . import views
from django.urls import path
urlpatterns = [
#add your urls here if you have
path('',views.index,name='index'),
]
html
{% extends "image/layout.html" %}
{% load static %}
{% block body %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Upload">
</form>
{% endblock %}