viewing images from django models - django-models

Im trying to add an image to my polls app, which i have set up as: upload_to='mysite/static/polls_app/question_pics'
but the wrong file path is used when I view the page:
GET /polls/1/static/polls_app/question_pics/
How can I go about editing this so Django uses the url where the image is saved?
Models.py
question_image = models.ImageField(upload_to='static/polls_app/question_pics', default=None, blank=True, null=True)
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
Views.py
model = Question
template_name = 'polls_app/detail.html'
detail.html
<img src="{{ question.question_image.url }}" alt="image">
urls.py
path('<int:pk>/', views.DetailView.as_view(), name='detail'),

Add below in urls.py
from django.views.static import serve
from django.urls import include,re_path
from . import settings
// Your code as it is
urlpatterns += [re_path(r'^media/(?P.*)', serve, {'document_root': settings.MEDIA_ROOT})]
This should help !!

Related

How to upload templates and static files to a django app?

I am trying to upload webpages to my django server.
They are all project of mine, and I want to be able to add more projects in the future through the admin panel:
I am working in an app called projects
This is the model I am using:
from django.db import models
from django.utils.timezone import now
from django.core.files.storage import FileSystemStorage
# Create your models here.
class Project(models.Model):
class ProjectType(models.TextChoices):
PYTHON = 'Python'
JAVASCRIPT = 'Javascript'
REACTJS = 'React.js'
REACTNATIVE = 'React Native'
JAVA = 'Java'
C = 'C'
CPP = 'C++'
def upload_location_photo(instance, filename):
return f'photos/projects/{instance.slug}/{filename}'
def upload_location_template(instance, filename):
#I want to get into, app: projects, folder: templates/projects
return f'projects/templates/projects/{instance.slug}/{filename}'
def upload_location_static(instance, filename):
#I want to get into, app: projects, folder: static/projects
return f'projects/static/projects/{instance.slug}/{filename}'
slug = models.CharField(max_length=200, unique=True)
project_type = models.CharField(max_length=50, choices=ProjectType.choices, default=ProjectType.JAVASCRIPT)
title = models.CharField(max_length=150)
description = models.TextField(blank=True)
date_completed = models.DateTimeField(default=now, blank=True)
photo_main = models.ImageField(upload_to=upload_location_photo)
photo_1 = models.ImageField(upload_to=upload_location_photo, blank=True)
photo_2 = models.ImageField(upload_to=upload_location_photo, blank=True)
photo_3 = models.ImageField(upload_to=upload_location_photo, blank=True)
#FILE UPLOAD OF JS APPS
file_html = models.FileField(upload_to=upload_location_template, max_length=100, blank=True)
file_css = models.FileField(upload_to=upload_location_static, max_length=100, blank=True)
file_js = models.FileField(upload_to=upload_location_static, max_length=100, blank=True)
This is in a django app called projects.
This issue is, that the html, css, and js files are being uploaded into: media/projects/static/projects and media/projects/templates/projects
instead of going into my app, they are being saved in the global media folder, how can I stop this, and direct them into my app's template and static folder?
Sorry, I asked that question too soon, however now I can help someone else hopefully!
I needed to add a few lines of code:
new imports:
import os
from django.core.files.storage import FileSystemStorage
from django.conf import settings
Adjust my upload location functions:
def upload_location_template(instance, filename):
return f'{instance.slug}/{filename}'
def upload_location_static(instance, filename):
return f'{instance.slug}/{filename}'
Create new storage locations, and add them as arguments to my FileFields:
template_storage = FileSystemStorage(location=os.path.join(settings.BASE_DIR, 'projects/templates/projects/'))
static_storage = FileSystemStorage(location=os.path.join(settings.BASE_DIR, 'projects/static/projects/'))
file_html = models.FileField(upload_to=upload_location_template, storage=template_storage, max_length=100, blank=True)
file_css = models.FileField(upload_to=upload_location_static, storage=static_storage, max_length=100, blank=True)
file_js = models.FileField(upload_to=upload_location_static, storage=static_storage, max_length=100, blank=True)
It is now working perfectly, used this answer here: https://helperbyte.com/questions/177113/django-multiple-media-root

Django adding letters and numbers to imageField url

I have an ImageField in a django model
image = models.ImageField(upload_to='images')
My media root is set like so in settings.py
MEDIA_ROOT = '/art/'
But when I upload select a gif url for the Imagefield, the url does not save as /art/images
I get this error message in Django Admin when I upload the url for the gif "Barnie.gif", which is stored at art/images/Barnie.gif
Art with ID "1/change/images/Barnie_L2fAl.gif" doesn't exist. Perhaps it was deleted?
I had the same problem. I solved it by adding the following imports:
from django.conf import settings
from django.conf.urls.static import static
I also added the following urlpatterns:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I wanted to try to get away with not doing all the config stuff, but you do have to do that.
In my base app urls.py I added:
from django.conf import settings
from django.conf.urls.static import static
and at the end of the urls list I added:
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Then in my settings.py I added:
MEDIA_ROOT = os.path.join(BASE_DIR, '/art/images')
MEDIA_URL = '/images/'

Creating new wagtail home_page

I changed a bit wagtail 0001_initial.py and 0002_chreate_homepage.py and if i do migrate/makemigrations i get Server Error
Here is how i changed these files
0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-02-11 16:32
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('wagtailcore', '0040_page_draft_title'),
]
operations = [
migrations.CreateModel(
name='HomePage',
fields=[
('page_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
('tournament_section_title', models.CharField(blank=True, help_text='Title to display above the next matches', max_length=255, null=True)),
('matches_section_title', models.CharField(blank=True, help_text='Title to display above the next matches', max_length=255, null=True)),
('news_section_title', models.CharField(blank=True, help_text='Title to display above the News section on Home page', max_length=255, null=True)),
('presentation_screen_section_title', models.CharField(blank=True, help_text='Title to display above the News section on Home page', max_length=255, null=True)),
('matches_section', models.ForeignKey(blank=True, help_text='Choose a page to link to for the Matches Page', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailcore.Page', verbose_name='Choose ')),
('news_section', models.ForeignKey(blank=True, help_text='Choose a page to link to for the News Page.', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailcore.Page', verbose_name='News')),
('presentation_screen_section', models.ForeignKey(blank=True, help_text='Choose a page to link to for the Presentation Screen Page.', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailcore.Page', verbose_name='Presentation Screen')),
('tournament_section', models.ForeignKey(blank=True, help_text='Choose a page to link to for the Matches Page', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailcore.Page', verbose_name='Choose ')),
],
options={
'abstract': False,
},
bases=('wagtailcore.page',),
),
]
and 0002_chreate_homepage.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def create_homepage(apps, schema_editor):
# Get models
ContentType = apps.get_model('contenttypes.ContentType')
Page = apps.get_model('wagtailcore.Page')
Site = apps.get_model('wagtailcore.Site')
HomePage = apps.get_model('base.HomePage')
# Delete the default homepage
# If migration is run multiple times, it may have already been deleted
Page.objects.filter(id=2).delete()
# Create content type for homepage model
homepage_content_type, __ = ContentType.objects.get_or_create(
model='homepage', app_label='home')
# Create a new homepage
homepage = HomePage.objects.create(
title="Home",
draft_title="Home",
slug='home',
content_type=homepage_content_type,
path='00010001',
depth=2,
numchild=0,
url_path='/home/',
)
# Create a site with the new homepage set as the root
Site.objects.create(
hostname='localhost', root_page=homepage, is_default_site=True)
def remove_homepage(apps, schema_editor):
# Get models
ContentType = apps.get_model('contenttypes.ContentType')
HomePage = apps.get_model('base.HomePage')
# Delete the default homepage
# Page and Site objects CASCADE
HomePage.objects.filter(slug='home', depth=2).delete()
# Delete content type for homepage model
ContentType.objects.filter(model='homepage', app_label='home').delete()
class Migration(migrations.Migration):
dependencies = [
('base', '0001_initial'),
]
operations = [
migrations.RunPython(create_homepage, remove_homepage),
]
Which way I have to do this, so if I deploy my project to heroku and run migrate it will automatically create HomePage that i changed.
my Project tree
-Project/
|-requirements
|-treichle-cup
|-base
|-search
|-settings
|-static
|-templates
In site settings my HomePage is exist and set as Root Page

Show ImageField in Angular template

I'm using Django with Angular to build a blog, and would like to use Django's built-in ImageField. <img src="{{ post.image }}"> is not rendering the image though. It is rendering the other fields though (This HTML - <span>{{ post.title }}</span> - works fine).
models.py
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=200, blank=True, null=True)
date_added = models.DateField(editable=True)
author = models.ForeignKey(User)
image = models.ImageField(blank=True, null=True)
text = models.TextField(null=True, blank=True)
def __str__(self):
"""Return a string representation of the model"""
return self.title
File strucrture>>
Be sure you have set MEDIA_ROOT in your settings.py as the absolute filesystem path to the directory that will hold user-uploaded files.
During development, be sure you have added settings.MEDIA_URL in your urls.py, as described in the documentation

GAE upload image then dynamically serve the image

I'm trying to make a simple app on GAE that allows a user to enter a url to an image and a name. The app then uploads this image to the Datastore along with its name.
After the upload the page self redirects and then should send the image back to the client and display it on their machine.
After running all I get is a Server error. Since I am new to GAE please could someone tell me if my code is at least correct.
I can't see what is wrong with my code. (I have checked for correct indentation and whitespace). Below is the code:
The python:
import jinja2 # html template libary
import os
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
import urllib
import urllib2
import webapp2
from google.appengine.ext import db
from google.appengine.api import urlfetch
class Default_tiles(db.Model):
name = db.StringProperty()
image = db.BlobProperty(default=None)
class MainPage(webapp2.RequestHandler):
def get(self):
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render())
class Upload(webapp2.RequestHandler):
def post(self):
# get information from form post upload
image_url = self.request.get('image_url')
image_name = self.request.get('image_name')
# create database entry for uploaded image
default_tile = Default_tiles()
default_tile.name = image_name
default_tile.image = db.Blob(urlfetch.Fetch(image_url).content)
default_tile.put()
self.redirect('/?' + urllib.urlencode({'image_name': image_name}))
class Get_default_tile(webapp.RequestHandler):
def get(self):
name = self.request.get('image_name')
default_tile = get_default_tile(name)
self.response.headers['Content-Type'] = "image/png"
self.response.out.write(default_tile.image)
def get_default_tile(name):
result = db.GqlQuery("SELECT * FROM Default_tiles WHERE name = :1 LIMIT 1", name).fetch(1)
if (len(result) > 0):
return result[0]
else:
return None
app = webapp2.WSGIApplication([('/', MainPage),
('/upload', Upload),
('/default_tile_img', Get_default_tile)],
debug=True)
The HTML:
<html>
<head>
<link type="text/css" rel="stylesheet" href="/stylesheets/main.css" />
</head>
<body>
<form action="/upload" method="post">
<div>
<p>Name: </p>
<input name="image_name">
</div>
<div>
<p>URL: </p>
<input name="image_url">
</div>
<div><input type="submit" value="Upload Image"></div>
</form>
<img src="default_tile_img?{{ image_name }}">
</body>
</html>
Any help at all will be so much appreciated. Thanks you!
UPDATE
Thanks to Greg, I know know how to view error logs. As Greg said I was missing a comma, I have updated the code above.
The app now runs, but when I upload an image, no image shows on return. I get the following message in the log:
File "/Users/jamiefearon/Desktop/Development/My Programs/GAE Fully functional website with css, javascript and images/mywebsite.py", line 53, in get
default_tile = self.get_default_tile(name)
TypeError: get_default_tile() takes exactly 1 argument (2 given)
I only passed one argument to get_default_tile() why does it complain that I passed two?
You're missing a comma after ('/upload', Upload) in the WSGIApplication setup.
use this python code
import jinja2 # html template libary
import os
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
import urllib
import urllib2
import webapp2
from google.appengine.ext import db
from google.appengine.api import urlfetch
class Default_tiles(db.Model):
name = db.StringProperty()
image = db.BlobProperty(default=None)
class MainPage(webapp2.RequestHandler):
def get(self):
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render())
class Upload(webapp2.RequestHandler):
def post(self):
# get information from form post upload
image_url = self.request.get('image_url')
image_name = self.request.get('image_name')
# create database entry for uploaded image
default_tile = Default_tiles()
default_tile.name = image_name
default_tile.image = db.Blob(urlfetch.Fetch(image_url).content)
default_tile.put()
self.redirect('/?' + urllib.urlencode({'image_name': image_name}))
class Get_default_tile(webapp2.RequestHandler):
def get_default_tile(self, name):
result = db.GqlQuery("SELECT * FROM Default_tiles WHERE name = :1 LIMIT 1", name).fetch(1)
if (len(result) > 0):
return result[0]
else:
return None
def get(self):
name = self.request.get('image_name')
default_tile = self.get_default_tile(name)
self.response.headers['Content-Type'] = "image/png"
self.response.out.write(default_tile)
app = webapp2.WSGIApplication([('/', MainPage),
('/upload', Upload),
('/default_tile_img', Get_default_tile)],
debug=True)

Resources