Picture cannot display Django - python

I've issue related with displaying image from Model.I have caption instead of picture. I don't know what is the cause of that .
from django.db import models
class Games(models.Model):
name = models.CharField(max_length=250)
platform = models.CharField(max_length=500)
genre = models.CharField(max_length=100)
language = models.CharField(max_length=100)
image = models.ImageField(upload_to='Images_game',default='' )
# def __str__ (self):
# return self.Name
class Game_detail(models.Model):
game = models.ForeignKey(Games,on_delete=models.CASCADE)
subcryption = models.TextField()
publisher = models.CharField(max_length=250)
date_of_publish = models.DateField()
class Order(models.Model):
person_name = models.CharField(max_length=24)
person_surname = models.CharField(max_length=24)
street = models.CharField(max_length=45)
city= models.CharField(max_length=45)
views.py
from django.shortcuts import render
from .models import Games,Game_detail,Order
from django.shortcuts import render,get_object_or_404,redirect
from django.views.generic import ListView,DetailView,CreateView
class IndexView(ListView):
template_name ='games/list.html'
context_object_name = 'all_games'
model = Games
def get_queryset(self):
return Games.objects.all()
class Item_Detail (DetailView):
context_object_name = 'object'
template_name ='games/detail.html'
model = Games # tu jest wazna zmiana
def get_context_data(self, **kwargs):
context = super(DetailView,self).get_context_data(**kwargs)
context['Game_detail']=Game_detail.objects.all()
return context
class Create_order (CreateView):
template_name ='games/create.html'
model= Order
fields = ['person_name','person_surname','street','city']
settings.py
from django.conf.urls import include,url
from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^games/',include("games.urls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
list.html template
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
{% for obj in all_games%}
<a href ='{%url "detail" pk=obj.pk%}'>{{obj.name}}</a>
{{obj.image}}
{{obj.platform}}
{{obj.genre}}
{{obj.language}}
{% endfor %}
</body>
</html>
I think it would be problem with right track to the picture . I added the picture in database and image upload to folder

You will need to specify in your template
<img src="{{obj.image.url}}" />.
You are storing the upload path in the database, so in the src you can have the obj.image entered and should be able to see the image just fine.

Related

model forms were not generated automatically using django model forms

I'm creating Django forms using model forms because u I wanted the forms to be created automatically, but when I created this code the forms do not appear in the index.html page
models.py
from django.db import models
class BaseCase(models.Model):
base_case_name = models.CharField(primary_key=True, max_length=255)
version = models.TextField(blank=True, null=True)
default = models.TextField(blank=True, null=True) # This field type is a guess.
class Meta:
managed = False
db_table = 'base_case'
forms.py
from django import forms
from SFP.models import *
class BaseCaseForm(forms.ModelForm):
class Meta :
model = BaseCase
fields='__all__'
views.py
from django.shortcuts import render,redirect
from .models import *
from .forms import *
def addbc(self, request):
bcform=BaseCaseForm(request.POST)
bcform.save()
basecasename = bcform.cleaned_data['post']
version = bcform.cleaned_data['post']
default = bcform.cleaned_data['post']
bcform = BaseCaseForm()
return redirect('index.html')
args = {'bcform':bcform,
'basecasename': basecasename,
'version': version,
'default' :default}
return render(request, 'index.html', args)
index.html
<!DOCTYPE html>
<html>
<head>
<title>S&FP</title>
</head>
<body>
<h1>Forms</h1>
{% csrf_token %}
{{ bcform }}
<input type="submit" value="add">
</body>
</html>
and i think that this is important too
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^$', views.addbc),
]
I was expecting the form fields to be generated automatically but they don't appear!
You can try CreateView which will create forms for your model. Find more about it in the docs
In your case, create a view like this:
views.py
class BaseCaseCreate(CreateView):
model = BaseCase
template_name = 'index.html'
success_url = reverse_lazy('app:home')
fields = ('base_case_name','version','default')
index.html
<!DOCTYPE html>
<html>
<head>
<title>S&FP</title>
</head>
<body>
<h1>Forms</h1>
{% csrf_token %}
{{ form }}
<input type="submit" value="add">
</body>
I hope this helps.

How and where should I store the conversion code for image files in Django?

I created a simple form in Django of which it contains only a single form input field i.e image field. My aim is to allow a user to upload an image file i.e JPEG, JPG, SVG, PNG. Once uploaded, I want to write some code that'll convert the image file to PNG and then store it in my database. How should I write this code and where do I write it? You can view my current code below. I'm a beginner in Django and could use some help.
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
website/urls.py:
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('myapp.urls')),
]
urlpatterns = urlpatterns + static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns = urlpatterns + static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
models.py
from django.db import models
class Image(models.Model):
"""Image upload model"""
image = models.ImageField(upload_to = 'media', default = 'media/sample.png')
created_date = models.DateTimeField(auto_now = True)
def __str__(self):
return str(self.id)
forms.py
from django import forms
from myapp.models import Image
class ImageForm(forms.ModelForm):
"""Image upload form"""
class Meta:
model = Image
exclude = ('created_date',)
views.py
from django.shortcuts import render
from django.db import models
from django.views.generic import TemplateView, CreateView
from myapp.forms import ImageForm
from django.urls import reverse_lazy
from PIL import Image
class BaseView(TemplateView):
template_name = "base.html"
class ImageView(CreateView):
template_name = "insert_image.html"
form_class = ImageForm
success_url = reverse_lazy("base")
insert_image.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title> Insert an image </title>
</head>
<body>
<h1> Please upload an image below </h1>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<button type="submit"> Submit </button>
</form>
</body>
</html>
base.html
<!DOCTYPE html>
<html>
<head>
<title> Thanks! </title>
</head>
<body>
<h1> Thanks for uploading! </h1>
<button> <a href = '{% url "insert_image" %}' style="text-decoration:
none;"> Return </button> </a>
</body>
</html>
The answer is "pyrsvg" - a Python binding for librsvg.
There is an Ubuntu python-rsvg package providing it. Searching Google for its name is poor because its source code seems to be contained inside the "gnome-python-desktop" Gnome project GIT repository.
I made a minimalist "hello world" that renders SVG to a cairo surface and writes it to disk:
from django.db import models
import os
from PIL import Image
class Image(models.Model):
"""Image upload model"""
image = models.ImageField(upload_to = get_directory_path, default = 'media/sample.png')
created_date = models.DateTimeField(auto_now = True)
def __str__(self):
return str(self.id)
def get_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
file_extension = os.path.splitext(filename)
if file_extension[1] in ['.jpg','.png','.jpeg','.svg']:
if file_extension[1] != '.svg':
filename=file_extension[0]+'.png'
dir = 'Images'
else:
import cairo
import rsvg
img = cairo.ImageSurface(cairo.FORMAT_ARGB32, 640,480)
ctx = cairo.Context(img)
## handle = rsvg.Handle(<svg filename>)
# or, for in memory SVG data:
handle= rsvg.Handle(None, str(<svg data>))
handle.render_cairo(ctx)
filename=img.write_to_png("svg.png")
dir = 'Images'
else:
dir="others"
path = '{0}/{1}'.format(dir, filename)
return path
Update: as of 2014 the needed package for Fedora Linux distribution is: gnome-python2-rsvg. The above snippet listing still works as-is.
In your ImageView class you can override form_valid
class ImageView(CreateView):
[...]
def form_valid(self, form):
uploaded_image = form.instance
[do your convert code here]
return super(ImageView, self).form_valid(form)
you could also use post_save signal.
This is the exact way you can do please reply back if you face any problen and do vote my answer :--
from django.db import models
import os
from PIL import Image
class Image(models.Model):
"""Image upload model"""
image = models.ImageField(upload_to = get_directory_path, default = 'media/sample.png')
created_date = models.DateTimeField(auto_now = True)
def __str__(self):
return str(self.id)
def get_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
file_extension = os.path.splitext(filename)
if file_extension[1] in ['.jpg','.png','.jpeg']:
filename=file_extension[0]+'.png'
dir = 'Images'
else:
dir="others"
path = '{0}/{1}'.format(dir, filename)
return path

How can I show model data's contents in html file?

I wrote in results.html,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Score</title>
</head>
<body>
<h1>Score</h1>
<h2>Your score is {{ scoreresults.result }}</h2>
</body>
</html>
But now, this part {{ user.result }} of <h2>Your score is {{ user.result }}
</h2> is blank in my browser.
I wrote in models.py
from django.db import models
from django.contrib.auth.models import User
class ImageAndUser(models.Model):
user = models.ForeignKey("auth.User", verbose_name="imageforegin")
result = models.CharField(max_length=64, null=True)
def __str__(self):
return '{} {}'.format(self.user,self.id)
So,ImageAndUser model has result data.
I cannot understand how to designate ImageAndUser model in results.html.
Furthermore,
I wrote in serializer.py
from .forms import UserImageForm
from rest_framework import serializers
from .models import ImageAndUser
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = ImageAndUser
fields =(
'image',
'result',
'user',
'id',
)
read_only_fields = (
'user',
)
def create(self, attrs):
attrs['user'] = self.context.get('request').user
print(attrs)
return super(ImageSerializer,self).create(attrs)
Now,I wrote in views.py
def scoreresults(request):
d = {
'scoreresults': ImageAndUser.objects.result(),
}
return render(request, 'registration/accounts/results.html', d)
in urls.py
from django.conf.urls import url
from . import views
from django.views.generic import TemplateView
urlpatterns = [
url(r'^scoreresults$', TemplateView.as_view(template_name='registration/accounts/results.html'),
name='tcresults'),
]
But it did not work.
So,how can I fix this?
You have a lot of bits here but none of them are linked up to one another.
The main problem is your url; it does not point to your view. Instead of using a TemplateView declared in the url itself, you should point it to the view function you have defined:
url(r'^scoreresults$', views.scoreresults, name='tcresults')
You don't seem to be using the serializer at all; and you don't need it.

Django Class-based ViewCreate and ViewUpdate file upload

I have a project where I wish to upload an image with the Django auto generated class-based views, and it works on the admin side, but I don't know what I'm missing to make it work from an HTML page. I've searched the web with a little luck or not enough clarification.
So maybe someone can tell me what I'm missing. Here is my code:
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'project/app/media_cdn')
models.py
from django.db import models
from django.core.urlresolvers import reverse
class Article(models.Model):
title = models.CharField(max_length = 200)
...
thumbnail = models.FileField(null = True, blank = True)
...
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('articles_detail', kwargs={'pk': self.pk})
class Meta:
ordering = ['-pk']
views.py
from django.shortcuts import render
from app.models import Article
from django.views.generic import *
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
# Create your views here.
def index(request):
return render(request, 'index.html')
class ArticleList(ListView):
model = Article
class ArticleDetail(DetailView):
model = Article
class ArticleCreate(LoginRequiredMixin, CreateView):
model = Article
fields = ['title', 'description', 'abstract', 'thumbnail', 'author', 'category', 'publishDate']
class ArticleUpdate(LoginRequiredMixin, UpdateView):
model = Article
fields = ['title', ..., 'thumbnail', ...]
class ArticleDelete(LoginRequiredMixin, DeleteView):
model = Article
success_url = reverse_lazy('articles_list')
urls.py
from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from app import views, auth
urlpatterns = [
url(r'^admin/',admin.site.urls),
...
url(r'^articles/(?P<pk>[0-9]+)/$', views.ArticleDetail.as_view(), name = 'articles_detail'),
url(r'^articles/create/$', views.ArticleCreate.as_view(), name = 'articles_create'),
url(r'^articles/update/(?P<pk>[0-9]+)/$', views.ArticleUpdate.as_view(), name = 'articles_update'),
url(r'^articles/delete/(?P<pk>[0-9]+)/$', views.ArticleDelete.as_view(), name = 'articles_delete'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
article_form.html
{% extends 'layout.html' %}
{% block content %}
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
As much as I was able to gather, I managed to follow all the steps but I still can't get the thumbnail to update when uploading from articles/create/ and articles/update/.../
Thanks in advance.

Showing images on my homepage using the data from my Django Model

Would like to simplely show multiple pictures from my model data that I inputted via the Admin in my template file between the UL tag. I am having trouble rendering the data to show the image. I dont need to route anything in URL.py yet, just need to pollute the images on my homepage first. Can someone please help troubleshoot my issue? Thank you!
Models.py
class Product(models.Model):
name = models.CharField(max_length=254, blank=True, null=True)
description = models.TextField(blank=True, null=True)
color_name = models.CharField(max_length=254, null=True, blank=True)
size_types = models.CharField(max_length=7, null=True, blank=True)
product_price = models.DecimalField(max_digits=9,decimal_places=2)
old_price = models.DecimalField(max_digits=9,decimal_places=2, blank=True,default=0.00) #To show original price if, new price has been added
product_tags = models.CharField(max_length=254, null=True, blank=True, help_text='Comma-delimited set of SEO keywords for product tag area')
novelty = models.CharField(max_length=254, null=True, blank=True)
product_website = models.URLField(max_length=200, null=True, blank=True) #To show other sites to Users, where they can purchase the particular product
image = models.ImageField(upload_to='images/products/main',max_length=100, null=True) #For the argument upload_to, will add to the static folder and generated image will be stored in suing that path specified
slug = models.SlugField(max_length=255, unique=True, help_text='Unique value for product page URL, created from name.')
#This shows when each item was uploaded & by who, to the User
uploaded_by = models.CharField(max_length=254, blank=True, null=True)
uploaded_at = models.DateTimeField(auto_now=True)
#For Admin Purposes, to track and see which if still active by for administrative users only
is_active = models.BooleanField(default=True)
#Foreign Keys & other relationships
designer = models.ForeignKey(Designer)
boutique = models.ForeignKey(Boutique)
category = models.ForeignKey(ProductCategory)
#Metadata
class Meta:
verbose_name = _("Product")
verbose_name_plural = _("Products")
#Helps return something meaningful, to show within the admin interface for easy interaction
def __unicode__(self):
return "{0}".format(self.name)
Forms.py
from __future__ import unicode_literals
from django import forms
from django.forms import extras, ModelForm
from products.models import Designer, Product, ProductCategory, Boutique
class DesignerForm(ModelForm):
class Meta:
model = Designer
class ProductForm(ModelForm):
class Meta:
model = Product
class BoutiqueForm(ModelForm):
class Meta:
model = Boutique
class ProductCategoryForm(ModelForm):
class Meta:
model = ProductCategory
Views.py
from __future__ import unicode_literals
from django.http import Http404, HttpResponseForbidden
from django.shortcuts import redirect, get_object_or_404
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.views.generic import DetailView
from django.contrib import auth, messages
from django.contrib.sites.models import get_current_site
from django.shortcuts import render
from products.forms import ProductForm, ProductCategoryForm
from products.forms import BoutiqueForm
from products.forms import DesignerForm
from products.models import Boutique, Product, ProductCategory, Designer
class ProductView(DetailView):
model = Product
context_object_name = "task"
Template
{% extends "site_base.html" %}
{% load i18n %}
{% block body %}
<div id="main" role="main">
<ul id="tiles">
<li>
{% for task in products %}
<img src="{{MEDIA_URL}}images/product/main {{task.image.url}}" />
{% endfor %}
</li>
</ul>
</div>
{% endblock %}
There are some odd things in this code.
Firstly, you want to do something with all products. So why are you using a DetailView, which is for selecting and displaying a single item? You need to use a ListView, which will pass a list of products.
Secondly, for some reason you override context_object_name to be "task". But then in the template, you iterate through "products" - a name that is not provided. If you've called the context object "task", that's what you should be iterating over.
Figured out what I was doing wrong!
Apparently I needed to go within my urls and change my already existing TemplateView in the first url tuple:
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import TemplateView
from django.contrib import admin
urlpatterns = patterns('',
url(r"^$", TemplateView.as_view(template_name="homepage.html"), name="home"),
url(r'^admin/', include(admin.site.urls)),
url(r"^account/", include("account.urls")),
url(r'^likes/', include('likes.urls')),
)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and change the URL tuple to a ListView, to generate the image from my django models.
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import ListView
from products.models import Product
from django.contrib import admin
urlpatterns = patterns('',
url(r"^$", ListView.as_view(
template_name="homepage.html",
model = Product,
context_object_name = "products",
), name="home"),
url(r'^admin/', include(admin.site.urls)),
url(r"^account/", include("account.urls")),
url(r'^likes/', include('likes.urls')),
)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Categories