Python django image upload is not working

2024/11/20 11:29:01

Python Django image upload is not working when I am adding data and click on submit button not give a any response and also not upload any data in the database.

models.py fisrst of all i add model file.

# Create your models here.
from django.db import models
class Car(models.Model):carname=models.CharField(max_length=50)carmodel = models.CharField(max_length=50)carimage = models.ImageField(upload_to='images/')price=models.CharField(max_length=15)average=models.CharField(max_length=20)gear=models.CharField(max_length=200)passengers = models.CharField(max_length=200)type=models.CharField(max_length=200)Insurance=models.CharField(max_length=200)class Meta:db_table="car"

forms.py then i create a form.py.

from django import forms
from  carapp.models import Carclass CarForm(forms.ModelForm):class Meta:model=Carfields="__all__"

also add this two line in settings.py

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

urls.py then i give a path of method.

from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from carapp import carviews
urlpatterns = [path('admin/', admin.site.urls),#this is for admin userpath('savecar',carviews.savecar),path('showcar', carviews.showcar)
]
if settings.DEBUG:urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

carviews.py

then I created an API method.

from django.shortcuts import render,redirect
from carapp.forms import CarForm
from carapp.models import Car
from django.core.paginator import Paginator, EmptyPage, InvalidPagedef savecar(request):if request.method == "POST":form= CarForm(request.POST)if form.is_valid():try:form.save()return redirect("/showcar")except:passelse:form = CarForm()return render(request,"savecar.html",{'form':form})def showcar(request):car_list = Car.objects.all().order_by('-id')paginator = Paginator(car_list, 5)try:page=int(request.GET.get('page','1'))except:page=1try:cars= paginator.page(page)except(EmptyPage,InvalidPage):cars= paginator.page(paginator.num_pages)return render(request,"showcar.html",{'cars':cars})

this is savecar.html

  <div class="card-body"><form method="POST" action="/savecar" >{% csrf_token %}<div class="form-group"><label for="carname">Car Name</label><div class="col-sm-4">{{ form.carname }}</div></div><div class="form-group"><label for="carmodel">carmodel</label><div class="col-sm-4">{{ form.carmodel }}</div></div><div class="form-group"><label for="carimage">carimage</label><div class="col-sm-4">{{ form.carimage }}</div></div><div class="form-group"><label for="price">price</label><div class="col-sm-4">{{ form.price }}</div></div><div class="form-group"><label for="average">average</label><div class="col-sm-4">{{ form.average }}</div></div><div class="form-group"><label for="gear">gear</label><div class="col-sm-4">{{ form.gear }}</div></div><div class="form-group"><label for="passengers">passengers</label><div class="col-sm-4">{{ form.passengers }}</div></div><div class="form-group"><label for="type">type</label><div class="col-sm-4">{{ form.type }}</div></div><div class="form-group"><label for="Insurance">Insurance</label><div class="col-sm-4">{{ form.Insurance }}</div></div><button type="submit" class="btn btn-primary">Submit</button>&nbsp;<a class="btn btn-primary" href="/showcar">Back</a></form>   </div>

and yes i also install pillow

Answer

As per the documentation, you need to set the enctype on the form element and then pass in request.FILES to the form.

<form method="POST" action="/savecar" enctype="multipart/form-data">

And then in your views:

form = CarForm(request.POST, request.FILES)
https://en.xdnf.cn/q/118423.html

Related Q&A

Android bluetooth send message working first time only

I need to send string message from Raspberry PI to Android device. I am getting message first time only. After that it does not work at all. I am using PYTHON code in Raspberry PI. After first time, it…

Scraping data from href

I was trying to get the postcodes for DFS, for that i tried getting the href for each shop and then click on it, the next page has shop location from which i can get the postal code, but i am able to g…

Numpy - how to sort an array of value/key pairs in descending order

I was looking at the problem Fastest way to rank items with multiple values and weightings and came up with the following solution, but with two remaining issues:import numpy as np# set up values keys …

How to extract certain under specific condition in pandas? (Sentimental analysis)

The picture is what my dataframe looks like. I have user_name, movie_name and time column. I want to extract only rows that are first day of certain movie. For example, if movie as first date in the ti…

Flask app.run method does not work with WinPython 3.11.1 and next.js application: fetch failed

When using WinPython 3.10.5 I am able to debug my flask & next.js application using the flask debug mode (to enable hot reloads): app.run(debug=True, host=host, port=port)However, when using WinPyt…

Pythonic way to assign global administrator roles for Azure Active Directory

What specifically needs to be changed in the Python 3 code below in order to successfully assign the Global Administrator role for an Azure Active Directory Tenant to a given service principal? We tri…

Pandas calculating age from a date

I really need help with this one. My previous post was very bad and unclear - Im sorry - I wish I could delete but hopefully this one will be better.I need to calculate the age based off of a date (se…

Create new folders within multiple existing folders with python

I am looking for a way to create new folders within multiple existing folders. For example I have folders a,b,c.. etc and I want to create a new folder inside each of these existing folders and name th…

extract a column from text file

I have a a text file (huge amount of float numbers) with 25 columns. I want to extract column 14 and divide it by column 15. I could not extract this two columns. Codes:with open(sample for north.txt) …

kivy buildozer Compile Error pythonforandroid.toolchain

Compile platformCommand failed: /usr/bin/python3 -m pythonforandroid.toolchain create --dist_name=main -- bootstrap=sdl2 --requirements=kivy,python3 --arch armeabi- v7a --copy-libs --color=always --…