Django images upload fails - python

I am using django to upload a image to the database (POST request) and show the same in the site.
but for some reason my image is not uploading
models.py -
from django.db import models
class image_classification(models.Model):
pic=models.ImageField(upload_to='images')
views.py
from django.shortcuts import render
from .models import image_classification
from django.http import HttpResponse, HttpResponseRedirect
# def home(request):
# print('here you go ')
# images=image_classification.objects.all()
# url=images[len(images)-1].pic.url
# return render(request,'home.html',{'print':'everything is ok','image':url})
def home(request):
print('here you go ')
images=[]
images=image_classification.objects.all()
if len(images) > 0:
url=images[len(images)-1].pic.url
else:
url="place holder image url"
return render(request,'home.html',{'print':'everything is ok','image':url})
#handles uploaded images
def uploadImage(request):
print('image handling ')
img= request.FILES['image']
image=image_classification(pic=img)
image.save()
return HttpResponseRedirect('/')
url of the app
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('',views.home,name='home')
]
urlpatterns+= static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
url.py for project (incase you need this)
from django.contrib import admin
from django.urls import path, include
from ImageClassifier import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path("admin/", admin.site.urls),
path('', include('ImageClassifier.urls')),
]
lastly settings.py (not sure if this is needed)
MEDIA_ROOT= os.path.join(BASE_DIR,'ImageClassifier/media/')
MEDIA_URL= '/media/'
STATIC_URL = "/static/"
STATIC_ROOT= os.path.join(BASE_DIR, 'static')
and this is the error i am getting on the webpage while running

Make sure that you have the following code in project's urls.py:
from django.contrib import admin
from django.urls import path, include
from ImageClassifier import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path("admin/", admin.site.urls),
path('', include('ImageClassifier.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

I think the reason your image is not uploading is that you are not checking whether the request method is POST or not. Try below approach and see if it works.
views.py to save to database
from django.shortcuts import render, redirect
def image(request):
if request.method == "POST":
image = request.FILES.get("image")
pic = Image.objects.create(pic=image)
pic.save()
return redirect('/')
return render(request, "image.html", {})
template.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action=/image/ method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="image">
<input type="submit" value="upload file">
</form>
</body>
</html>
Url of project
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path("admin/", admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Url of app
from django.urls import path
from . import views
urlpatterns = [
path("image/", views.image, name="image"),
]
Lastly, settings.py
BASE_DIR = Path(__file__).resolve().parent.parent
MEDIA_ROOT = BASE_DIR / "media"
MEDIA_URL = "/media/"
P.S: Whenever you want to name a class, you should always use PascalCase not camelCase for the naming convention. You can read on python naming convention here. Hence you model will look something like this:
class ImageClassification(models.Model):
pic=models.ImageField(upload_to='images')

Related

Django - Recursion Error with static main.css

Running into a max recursion error when hitting my static main.css file in django. Need help identifying the issue and how to correct it.
Had no issues when my login/sign up pages were within my single dbManagementApp. After adding those to a new app (accounts) then adding the templates into a specific folder for each app, I received the below error message.
Debugger
In template ###, error at line 7
maximum recursion depth exceeded while calling a Python object
1 <!DOCTYPE html>
2 <html lang="en" dir="ltr">
3 <head>
4 <meta charset="utf-8">
5 <title>HOME</title>
6 {% load static %} <!-- load the static folder for css-->
7 <link rel="stylesheet" href="{% static 'main.css' %}">
Traceback
File "C:\Users\lukep\anaconda3\envs\djangoenv\lib\site-packages\django\template\base.py", line 766, in __init__
self.literal = float(var)
ValueError: could not convert string to float: "'main.css'"
My main urls.py:
from django.contrib import admin
from django.urls import path, include
from dbManagementApp import dbmviews
from accounts import accviews
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('dbManagementApp.dbmurls')),
path('accounts/', include('accounts.accurls'))
]
dbManagementApp/dbmurls.py
from django.urls import path
from . import dbmviews
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', dbmviews.home, name='home'),
path('aboutus/', dbmviews.aboutUs, name='aboutUs'),
path('pricing/', dbmviews.pricing, name='pricing'),
path('contact/', dbmviews.contact, name='contact'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
dbManagementApp/dbmviews.py
from django.shortcuts import render, redirect
from django.views import View
from .models import Doc
from .forms import DocumentForm
from django.contrib import messages
from django.http import HttpResponse
from django.http import JsonResponse
# Create your views here.
def home(request):
return render(request, 'dbmapp/index.html')
templates/dbmapp/index.html
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>HOME</title>
{% load static %} <!-- load the static folder for css-->
<link rel="stylesheet" href="{% static 'main.css' %}">
accounts/accurls.py
from django.urls import path
from . import accviews
urlpatterns = [
path('register/', accviews.register, name='register'),
path('login/', accviews.login, name='login')
]
accounts/accviews.py
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
def register(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form = UserCreationForm()
return render(request, 'registration/register.html', {'form':form})
def login(request):
return render(request, 'registration/login.html')
I'm not fully understand your problem, but I'd change 3 things
{% load static %} should be at the top of the html file
Move path('', include('dbManagementApp.dbmurls')), first (before admin)
Remove dir attribute in html.
Just a question, are you using {% extends 'whatever.html' %}?, it cause error from duplicating tags.

Routing for FormView Class

I have django_test project and defapp application in it.
I want to access form.html which MyView makes,
I am still confused about routing.
I can access localhost/defapp/ and show Hello, World
However how can I access the MyView class and show form.html?
in django_test/urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import include,url
urlpatterns = [
path('defapp/', include('defapp.urls')),
url(r'^s3direct/', include('s3direct.urls')),
path('admin/', admin.site.urls),
]
in defapp/views.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index')
]
in defapp/views.py
from django.shortcuts import render
# Create your views here.
from django.views.generic import FormView
from .forms import S3DirectUploadForm
def index(request):
return HttpResponse("Hello, world.")
class MyView(FormView):
template_name = 'form.html'
form_class = S3DirectUploadForm
in defapp/template/form.html
<html>
<head>
<meta charset="utf-8">
<title>s3direct</title>
{{ form.media }}
</head>
<body>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
</form>
</body>
</html>
If you're looking to know how to wire up a class based view in the urlconf, please checkout these docs on class based views.
The most direct way to use generic views is to create them directly in your URLconf. If you’re only changing a few attributes on a class-based view, you can pass them into the as_view() method call itself:
from django.urls import path
from django.views.generic import TemplateView
urlpatterns = [
path('about/', TemplateView.as_view(template_name="about.html")),
]
Additionally, the docs on as_view may prove helpful.

Django - issue with loading css

I've recently started learning Django and I've been having a lot of issues with implementing css into my code. I've found a lot of people with the same issue as me but I am still unable to find an answer.
Currently when I run open the website it give me this https://imgur.com/a/0N23s7b
And I'm not sure if this is because of the settings, the actual css or something in the html.
My html boilerplate
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>homepage</title>
<link rel="stylesheet" type="test/css" href="{% static'css/home.css' %}"/>
</head>
settings.py
DEBUG = True
STATIC_ROOT = ''
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
STATIC_URL = '/static/'
views.py
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from leatherbiscuit.views import index
urlpatterns = [
path('admin/', admin.site.urls),
path('', index),
]
if settings.DEBUG:
urlpatterns+=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urls.py
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import TemplateView
def index(request):
return render(request, 'index.html')
def home_view(request):
return HttpResponse(request, 'index.html')
You need to add a space between the name of the template tag and its parameters, so it should be:
&downarrow; a space between static and 'css/home.css'
{% static 'css/home.css' %}
The parser of the Django template engine has some peculiarities. For example, a tag should not be spanned over multiple lines, and like in Python's method calls one should first list the positional parameters and then the named parameters.

Visibility problem for static files -- django

I connected static files in django, but they won't connect, can you help?
settings:
STATICFILES_DIRS = [
"web_page/static",
]
STATIC_URL = '/static/'
STATIC_ROOT = '/static/'
index.html:
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="{% static "css/standart_template.css" %}" rel="stylesheet" type="text/css" >
<title>HouseVOP</title>
</head>
urls - projects:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('web_page.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urls - app:
from django.urls import path
from .views import FormListView, Success
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', FormListView, name = 'home'),
path('success/', Success, name = 'success')
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Before turning here, I searched many sites, so now I may simply not see something. In the first version of the code, I laid the path to the static files along with os.path.join (BASE_DIR, etc., but it did not work ...
try this one:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
dont use web_page/static.no need to.

Django: Static Image Not Loading

I'm having issues getting an image to load on my Django web application. I have used the online documentation and tried peoples suggestions that I found on Stackoverflow but I am still not having any luck getting it to load. Here is what I have:
Settings.py:
STATIC_DIR = os.path.join(BASE_DIR,'static')
INSTALLED_APPS = [
...
'django.contrib.staticfiles'
]
STATIC_URL = '/static/'
STATIC_ROOT = [STATIC_DIR,]
Urls.py:
from django.urls import path
from dir_app import views
from django.conf import settings
from django.conf.urls.static import static
app_name = 'dir_app'
urlpatterns=[
path('', views.tradesmen, name='tradesmen'),
path('register', views.register,name='register'),
path('user_login', views.user_login,name='user_login')
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Index.html: (Gist)
<!DOCTYPE html>
{% load static %}
<html>
<head>
</head>
<body>
<img src="{% static 'dir_app/tools.png' %}">
</body>
</html>
Here is where the image is stored:
DEBUG should be true if want to use django.conf.url.static
https://github.com/django/django/blob/926148ef019abcac3a9988c78734d9336d69f24e/django/conf/urls/static.py#L23
STATIC_ROOT should be a string, not a list.
https://docs.djangoproject.com/en/3.0/ref/settings/#std:setting-STATIC_ROOT

Categories