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

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

Related

viewing images from 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 !!

Displaying Python database on Flask web server

I'm working on a project that requires that I create a create a database, import data into it, and display it on a FLASK local server. I've created the database, but I'm confused as to what I need to do in order to display its tables on the server. I have it set up to display information via HTML through render_template and believe I've established a connection via config.py, but I'm not sure where to go from here. I've read the following guides, but I don't quite understand them. If anybody could assist, I would appreciate it.
http://flask.pocoo.org/docs/0.12/patterns/sqlalchemy/
http://flask-sqlalchemy.pocoo.org/2.3/config/
Below are the relevant files in the project root.
/project
config.py
database_insert.py
server.py
/app
/templates
index.html
__init__.py
models.py
routes.py
config.py
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
SECRET_KEY = 'you-will-never-guess'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////project/app.db'
SQLALCHEMY_TRACK_MODIFICATIONS = False
init.py
from flask import Flask, request, render_template
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
from app import routes, models
models.py
from app import db
class Lot(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(64), index=True)
spots = db.relationship('Spot', backref='author', lazy='dynamic')
def __repr__(self):
return '<Lot {}>'.format(self.username)
class Spot(db.Model):
id = db.Column(db.Integer, primary_key=True)
availability = db.Column(db.String(140))
spot_num = db.Column(db.String(140))
lot_id = db.Column(db.Integer, db.ForeignKey('lot.id'))
def __repr__(self):
return '<Spot {}>'.format(self.body)
routes.py
from app import app
from flask import Flask, request, render_template
#app.route('/')
#app.route('/index')
def index():
lot_details = {
'id': 'TEST_ID', #placeholder for testing purposes
'title': 'TEST_TITLE' #placeholder for testing purposes
}
return render_template('index.html', lot=lot_details)
index.html
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<p>Hello, World!</p>
<p>{{lot.id}}</p>
<p>{{lot.title}}</p>
</body>
At first, define helper method in your Spot model class.
class Spot(db.Model):
id = db.Column(db.Integer, primary_key=True)
availability = db.Column(db.String(140))
spot_num = db.Column(db.String(140))
lot_id = db.Column(db.Integer, db.ForeignKey('lot.id'))
def __repr__(self):
return '<Spot {}>'.format(self.body)
def dump(self):
return dict(id=self.id, title=self.title)
Then, in your flask route, you may query:
#app.route('/')
#app.route('/index')
def index():
lot_details = Lot.query.first().dump() # query first item
return render_template('index.html', lot=lot_details)

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

serve images using Google App Engine?

I am writing a simple application, that lets user upload images, and the application will show the image directly below the upload form. However I can't figure out how to show the image properly. I have tried several answers in stack overflow. None of them seem to answer the questions that I have. Could anyone please look at my code and see what I am doing wrong? Any help would be greatly appreciated.
import os
import urllib
import webapp2
from google.appengine.ext import db
import google.appengine.api.images
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
class MainHandler(webapp2.RequestHandler):
def get(self):
upload_url = blobstore.create_upload_url('/upload')
self.response.out.write('<html><body>')
self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
self.response.out.write("""Upload File: <input type="file" name="file"><br> <input type="submit"
name="submit" value="Submit"> </form>""")
#self.response.headers['Content-Type'] = 'image/png'
images = db.GqlQuery("select * from Images")
serving_url = ""
if images:
for x in images:
serving_url = google.appengine.api.images.get_serving_url(x.key(), 0, False, False)
self.response.out.write("""<div>Image:<img src="%s" </div> """ %serving_url)
else:
self.response.out.write("""<div>No Image Found</div>""")
self.response.out.write("""END</body></html>""")
class Images(db.Model):
image_db = db.BlobProperty()
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload_files = self.get_uploads('file') # 'file' is file upload field in the form
blob_info = upload_files[0]
self.redirect('/serve/%s' % blob_info.key())
class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, resource):
resource = str(urllib.unquote(resource))
blob_info = blobstore.BlobInfo.get(resource)
self.send_blob(blob_info)
app = webapp2.WSGIApplication([('/', MainHandler),
('/upload', UploadHandler),
('/serve/([^/]+)?', ServeHandler)],
debug=True)
You're doing a few things wrong here.
Firstly, you are correctly using blobstore to store the images. To store reference a blobstore image in a model, you should be using db.BlobReferenceProperty.
Secondly, you're not actually storing that reference in your UploadHandler:
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload_files = self.get_uploads('file') # 'file' is file upload field in the form
blob_info = upload_files[0]
instance = Images(image_db=blob_info)
instance.put()
self.redirect('/')
Finally, your GQL returns the Images instance, not of the blob. So your call to get_serving_url should be:
serving_url = images.get_serving_url(x.image_db)

Resources