Files in django template - python

i have a problem when i am trying to show files download link in django templates
message:
AttributeError: 'NoneType' object has no attribute 'split'
File "c:\users\ramin\appdata\local\programs\python\python36-32\Lib\wsgiref\simple_server.py", line 35, in close
self.status.split(' ',1)[0], self.bytes_sent
----------------------------------------
AttributeError: 'NoneType' object has no attribute 'split'
----------------------------------------
models.py:
from django.db import models
class Book(models.Model):
Title = models.CharField(max_length=100)
Writer = models.CharField(max_length=100)
Description = models.TextField()
Image = models.ImageField(default='default.jpg')
File = models.FileField(upload_to='PDF/')
def __str__(self):
return self.Title
views.py:
from django.views.generic.list import ListView
from . import models
class BookListView(ListView):
queryset = models.Book.objects.all()
template_name = 'Book/BookList.html'
template:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Books List</title>
</head>
<body>
{% for x in object_list %}
<h2>{{ x.Title }}</h2>
<img style="width:100px" src="{{ x.Image.url }}">
<p><a href="{{ x.File.url }}" download="{{ x.Title }}">Download</p>
{% endfor %}
</body>
</html>
when i click on download link , i can download file successfully but i see this message

Maybe the problem that you use a .txt file as the default image

try the following code, assuming that object_name is an object of that model:
filename = os.path.basename(object_name.file.name)
response = HttpResponse(object_name.file, content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
See the following part of the Django documentation on sending files directly: https://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment

Related

capture image and save it to database with django

I am trying to make a web app with django in which it clicks an image from the camera and saves the image to a database. How can that be implemented? if there is a source code available, kindly share a link to it. thank you
I came here hoping to find an answer; there not being one, I hereby offer mine ...
The trick is to encode the image and save it as a TextField.
The solution I provide is bit clunky in the way the images are read every time select_image.html is loaded, but I did that because my requirement is a bit more complex and this does the job. I assume you know how to get the image from the camera (which is equivalent to my reading it from file).
There are two templates, select_image.html and display_image.html. When select_image.html is called for the first time it reads .png images from file and saves the images to the database. When an image is selected it is retrieved from the database and displayed in display_image.html.
select_image.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Select Image</title>
</head>
<body>
<h1>Select Image</h1>
{% block content %}
<ul>
{% for image in images %}
<li>{{ image }}</li>
{% endfor %}
</ul>
{% endblock %}
</body>
</html>
display_image.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Display Image</title>
</head>
<body>
<h1>Display Image</h1>
{% block content %}
<img id="image" src="{{ image }}" alt="image">
{% endblock %}
<p></p>
Images
</body>
</html>
models.py
class Image(models.Model):
name = models.CharField(max_length=25, null= False, blank=False, default='image_name', unique=True)
image = models.TextField()
urls.py
urlpatterns = [
path('images', views.Images.as_view(), name='images'),
path('display-image/<str:image_name>/', views.DisplayImage.as_view(), name='display-image'),
]
views.py
from PIL import Image as PilImage
import io
import base64
import os
from .models import Image
class Images(View):
url = "images/select_image.html"
def get(self, request):
dir = <image file directory>
image_names = ['red', 'green', 'blue']
for image_name in image_names:
base_path = os.sep.join([dir, image_name])
path = '.'.join([base_path, 'png'])
pil_image = PilImage.open(path)
encoded_image = self._encode_image(pil_image)
Image.objects.get_or_create(name=image_name, image=encoded_image)
context = {'images': image_names}
return render(request, self.url, context)
#staticmethod
def _encode_image(image):
"""Return image encoded to base64 from a PIL.Image.Image."""
io_buffer = io.BytesIO()
image.save(io_buffer, format='PNG')
saved_image = io_buffer.getvalue()
encoded_image = ''.join(['data:image/jpg;base64,', base64.b64encode(saved_image).decode()])
return encoded_image
class DisplayImage(View):
url = "images/display_image.html"
def get(self, request, image_name):
image = get_object_or_404(Image, name=image_name)
context = {'image': image.image}
return render(request, self.url, context)

django 2 model function is not recognized inside of index.html

hey im new to django so don't be harsh !.im trying to make a blog in django . i need to map the posts in home page to the post page. for that .i have defined a function called get_absulute_url(self) in models.py but it is not recognized in index.html.
when i click on Links nothing happens...i'm not where did i made the mistake !
model.py
from django.db import models
from django.urls import reverse
import posts
# Create your models here.
class post(models.Model):
title=models.CharField(max_length=500)
content=models.TextField()
timestamp=models.DateTimeField(auto_now=False,auto_now_add=True)
updated= models.DateTimeField(auto_now=False,auto_now_add=True)
def get_absulute_url(self):
return reverse("posts:detail", kwargs={'id': self.id})
# return reverse(viewname=posts.views.posts_list,urlconf=any, kwargs={"id": self.id})
views.py
def posts_list(request):#list items
queryset=post.objects.all()
context={
"objectsList":queryset,
"title":"list"
}
return render(request,"index.html",context)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
{% for obj in objectsList %}
Link<br>
{{ obj.title }} <br>
{{ obj.content }} <br>
{{ obj.timestamp }} <br>
{{ obj.updated }} <br>
{{ obj.id }} <br>
{{ obj.pk }} <br>
{% endfor %}
</body>
</html>
url.py
from django.contrib import admin
from django.urls import path
from posts import views as posts_views
urlpatterns = [
path('create/',posts_views.posts_create),
path('<int:id>/', posts_views.posts_detail,name="detail"),
path('',posts_views.posts_list),
path('update/', posts_views.posts_update),
path('delete/', posts_views.posts_delete),
]
Change posts:detail to detail
return reverse("detail", kwargs={'id': self.id})
href="{% url "detail" id=obj.id %}"
Mapping may be the problem but it will throw error before execution.
Still add app_name = 'posts' in urls.py file of your app and try this may work or just use DetailView builtin class still getting error you better add post_detail view to the question above so we can get indepth picture of what you are looking for.

How do I solve ValueError: too many values to unpack (expected 2) in Django

I have been working at a Django App. Basically, the function of the app is to take the input as a subject name from user using a Form, take the details of progressed activities of that subject of that specific user, and save each of that detail in a single variable. It involved 3 Models viz. User Model (Django's default) Subject Model and Detail Model, finally it will use those variables to which details are assigned, and calculate the performance using fuzz_algo(), and then return the result in the form of Messages to the Template.
Everything seems to be fine, but when I click the button Calculate in the template users/performance_calculator.html, it give this error ValueError: too many values to unpack (expected 2) at this statement skype = Detail.objects.filter(subject__subject=sub, user__username=User.username).get('skype_session_attendance') in views.py
My views.py:
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import PerformanceCalculatorForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .models import Subject, Detail
from .fuzzy_logic_algo import fuzz_algo
def performanceCalculator(request):
skype = 0
internal_course = 0
prg_lab = 0
mid_marks = 0
final_marks = 0
sub = 0
if request.method == 'POST':
performance_form = PerformanceCalculatorForm(request.POST)
if performance_form.is_valid():
performance_form.save()
sub = performance_form.cleaned_data.get('subject')
skype = Detail.objects.filter(subject__subject=sub, user__username=User.username).get('skype_session_attendance')
internal_course = Detail.objects.filter(subject__subject=sub, user__username=User.username).get('internal_course_marks')
prg_lab = Detail.objects.filter(subject__subject=sub, user__username=User.username).get('programming_lab_activity')
mid_marks = Detail.objects.filter(subject__subject=sub, user__username=User.username).get('mid_term_marks')
final_marks = Detail.objects.filter(subject__subject=sub, user__username=User.username).get('final_term_marks')
result = fuzz_algo(skype, internal_course, prg_lab, mid_marks, final_marks)
messages.success(request, result)
return redirect('performance_calculator')
else:
performance_form = PerformanceCalculatorForm()
context = {
'performance_form': performance_form
}
return render(request, 'users/performance_calculator.html', context)
My models.py:
from django.db import models
from django.contrib.auth.models import User
class Subject(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
subject = models.CharField(max_length=100)
def __str__(self):
return '{} ({})'.format(self.subject, self.user.username)
class Detail(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
subject = models.OneToOneField(Subject, on_delete=models.CASCADE)
skype_session_attendance = models.FloatField()
internal_course_marks = models.FloatField()
programming_lab_activity = models.FloatField()
mid_term_marks = models.FloatField()
final_term_marks = models.FloatField()
def __str__(self):
return f'{self.subject, (self.user.username)} Details'
class Sub(models.Model):
s = models.CharField(max_length=100)
My forms.py:
from django import forms
from .models import Profile, Sub
class PerformanceCalculatorForm(forms.ModelForm):
subject = forms.CharField(max_length=100)
class Meta:
model = Sub
fields = ['subject']
My performance_calculator.html (template):
{% load static %}
{% load crispy_forms_tags %}
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{% static 'esacp/main.css' %}">
<title>Expert System for Assessing Programming Course Performance</title>
</head>
<body>
<main role="main" class="container">
<div class="row">
<div class="col-md-8">
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% if not request.user.is_superuser and not request.useris_staff %}
<div class="account-heading">
<h2>
Performance Calculator
</h2>
</div>
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4"></legend>
{{ performance_form|crispy }}
</fieldset>
<div class="from-group">
<button class="btn btn-outline-info" type="submit">Calculate</button>
</div>
</form>
</div>
{% endif %}
</div>
</div>
</main>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
The full error I get at the statement skype = Detail.objects.filter(subject__subject=sub, user__username=User.username).get('skype_session_attendance') is:
ValueError at /esacp/performance-calculator/
too many values to unpack (expected 2)
Request Method: POST
Request URL: http://localhost:8000/esacp/performance-calculator/
Django Version: 3.0.3
Exception Type: ValueError
Exception Value:
too many values to unpack (expected 2)
Exception Location: C:\environments\bsse_fyp\lib\site-packages\django\db\models\sql\query.py in build_filter, line 1247
Python Executable: C:\environments\bsse_fyp\Scripts\python.exe
Python Version: 3.8.1
Python Path:
['C:\\Users\\khubi\\OneDrive\\Desktop\\FYP\\test_phase',
'C:\\Users\\khubi\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip',
'C:\\Users\\khubi\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs',
'C:\\Users\\khubi\\AppData\\Local\\Programs\\Python\\Python38-32\\lib',
'C:\\Users\\khubi\\AppData\\Local\\Programs\\Python\\Python38-32',
'C:\\environments\\bsse_fyp',
'C:\\environments\\bsse_fyp\\lib\\site-packages']
Server time: Thu, 14 May 2020 07:12:19 +0000
I don't what has gone wrong and why it is showing this error. I read other threads here related to same issues, but their problem was they were using a 2D tuple instead of 1D tuple, or sometime dictionary or list issues, but I don't have any of that.
I have spent hours looking for the issue but I am unable to find one. Help will be really appreciated.
detail = Detail.objects.filter(...).first()
if detail:
skype = detail.skype_session_attendance
You are calling get method of QuerySet instance. Which requires kwargs and returns one instance or throws error if result is None or there are more than one instance.
To get skype value you must first get instance.

Django: Saving images uploaded through ImageField

I am trying to set up a webapp that accepts image uploads from a user, using ImageField, but I cant seem to figure out how to save the uploaded image. My media folder is empty even though there doesnt seem to be any errors.
Went through a lot of tutorials to no avail. I get the basic concept, create a form, model, set media in settings.py, handle upload in views, and I am getting a working view with a image upload form, but uploading an image does not save.
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py
urlpatterns = [
path('embed/', embed, name = 'embed'),
path('success', success, name = 'success'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
forms.py
class imguploadform(forms.ModelForm):
class Meta:
model = imgupload
fields = ['title', 'image']
models.py
class imgupload(models.Model):
title = models.CharField(max_length = 20)
image = models.ImageField(upload_to="media/images/", default = None)
def __str__(self):
return self.title
views.py
def embed(request):
if request.method == 'POST':
form = imguploadform(request.POST, request.FILES)
if form.is_valid():
newimg = imgupload(title=request.POST['title'], image=request.FILES['image'])
newimg.save()
return redirect('success')
else:
form = imguploadform()
return render(request, 'webapp/imgupload.html', {'form' : form})
def success(request):
return HttpResponse("Successfully uploaded")
imgupload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Image</title>
</head>
<body>
<form method = "post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
</body>
</html>
Another thing to note, the admin panel does not show the image model
The following code worked at my machine whoes os system is ubuntu18 with newest django and pillow
models.py
class Imgupload(models.Model):
title = models.CharField(max_length=20)
image = models.ImageField(upload_to="images/", default=None)
def __str__(self):
return self.title
views.py
def embed(request):
if request.method == "POST":
form = Imguploadform(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect("success")
else:
form = Imguploadform()
img = Imgupload.objects.last()
return render(request, "webapp/imgupload.html", {"form": form, "img": img})
def success(request):
return HttpResponse("Successfully uploaded")
imgupload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Image</title>
</head>
<body>
<form method = "post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
{% if img %}
Image uploaded latest:
<img src="{{ img.image.url }}">
{% endif %}
</body>
</html>

Images from Model in HTML Django 1.10

I am new to Django (1.10) so please excuse me. I am trying to visualise images from my model Clothes. Trying to create some sort of small webshop to train.
My Model:
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
class Clothes(models.Model):
user = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
description = models.TextField()
image = models.ImageField(upload_to = '/pic_folder/', default = '/pic_folder/None/no-img.jpg')
type_clothes = models.CharField(max_length=100)
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
class Meta:
verbose_name = "Kleding"
verbose_name_plural = "Kleding"
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
Views.py
from django.shortcuts import render
from django.utils import timezone
from .models import Clothes
def clothes_overview(request):
clothes= Clothes.objects.filter(published_date__lte=timezone.now())
return render(request, 'Clothes/clothes_overview.html', {'clothes' : clothes})
clothes_overview.html
{% load staticfiles %}
<html>
<head>
<title>WebShop</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="{% static 'css/clothes.css' %}">
</head>
<body>
<div>
<h1>Clothing WebShop</h1>
</div>
{% for cloth in clothes %}
<div>
<p>published: {{ cloth.published_date }}</p>
<h1>{{ cloth.title }}</h1>
// DISPLAY IMAGE HERE
<p>{{ cloth.text|linebreaksbr }}</p>
</div>
{% endfor %}
</body>
</html>
I have tried one option which I came across by searching Stack:
<img src="{{ cloth.image.url }}">
This helped others but still left my page showing broken images. I looked in the source using Google Chrome and found that the path is (specific for the hoodie.jpg):
<img src="pic_folder/hoodie.jpg">
I then tried another method:
<img src="{% static 'pic_folder/image.jpg' %}">
This did show the image.jpg in my browser multiple times! The path which I found is:
<img src="/static/pic_folder/image.jpg">
I somehow need to combine these two methods so that the images are loaded dynamically into the webpage. Could someone help me?
Djangos static template tag, allows you to pass in variables, so as you suggest - combine your approaches
<img src="{% static cloth.image.url %}">

Categories