Django: Checking if static file exists - python

Hope you're doing well. I've got a django view that needs to check to see if a static file with a known path exists.
I'm currently trying to use os.path.isfile(), but I have a feeling this is the wrong approach.
views.py:
import os
def knighthood_ceremony(warrior):
narration_path = static("polls/narrations/{}/{}.mp3".format(queen_name,warrior.name))
is_to_play_narration = os.path.isfile(narration_path)
settings.py:
STATIC_URL = '/static/'
Structure:
mysite
mysite
settings.py
polls
static
polls
narrations
5
1.mp3
views.py
otherproject
This gives local vars:
narration_path = '/static/polls/narrations/5/1.mp3'
is_to_play_narration = False
But, there is a file at:
C:\Users\{USER}\mysite\polls\static\polls\narrations\5\1.mp3
Why can't os.path.isfile see it? Any advice will be greatly appreciated!

Are you trying to read it via the URL or the STATIC_ROOT? If you are reading from the harddrive. Might be the error there

Related

cannot read static files after deploying my project on pythonanywhere PYTHON DJANGO

I dont know if I did this right but during development phase I placed all my static files on my project's main directory, it looks like this:
myproject
myapp
manage.py
myproject
- settings.py
- urls.py
...
static
- css
- somecssfile.css
- js
- somejsfile.js
...
templates
now my settings.py file looks like this:
STATICFILES_DIRS = [BASE_DIR / "static"]
STATIC_URL = '/static/'
after I deployed my project into pythonanywhere I added STATIC_ROOT:
STATIC_ROOT = '/home/jeremiramos/cvs/staticfiles/'
it does copy my static files to staticfiles folder when I do collectstatic on pythonanywhere console but it cannot read/load the static files I used on each and every page including admin page.
and my staticfiles settings on pythonanywhere looks like this:
I checked my console and I got some errors:
Refused to apply style from 'http://jeremiramos.pythonanywhere.com/static/css/index.css/' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
I've tried checking the forums of pythonanywhere.com but it doesn't seem to help.
Can anyone please explain what did I do wrong and what should I do? Thank you!
Since http://jeremiramos.pythonanywhere.com/static/css/index.css loads the actual file, it means that static file mappings are OK. Trying the url with trailing slash (as in the error message you've shown) gives 404 and MIME type error message might be a symptom of it. Remove trailing slash from the url and check if that solves the issue.

configuring django admin on elastic beanstalk

I am having a hard time configuring django admin to work on elastic beanstalk. I tried everything but it's still not working.
when I click on admin or my flag pages I get Server Error (500).
I have created a folder in my project called management in the root of my project, inside that I created another folder called commands and a file called createsu.py here is the content of the createsu.py
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
class Command(BaseCommand):
def handle(self, *args, **options):
if not User.objects.filter(username="admin").exists():
User.objects.create_superuser("admin", "admin#admin.com", "admin")
self.stdout.write(self.style.SUCCESS('Successfully created new super user'))
in my .config file I added this like of code
03_createsu:
command: "python manage.py createsu"
leader_only: true
after eb deploy and refreshing elastic beanstalk console when I try to go to the webpage I still get the same error. all my other pages are working, static files are working fine except my admin and flag pages because they are connected to the admin. I have been struggling with this for a week now. can someone please help me please.
#I fixed the issue.
#First typo was I forgot to add SITE_ID = 1 in my settings.py because I am using #flatpages.
#Second typo I didn't configure my static files correctly. I fixed it to this:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'assets'),
)
#Lastly createsu.py should be in the app folder not project folder.

Is there a way to define a remote template path for Django CMS

For the final stages of a Django CMS site we were able to serve the static files from remote:
Simply by changing the setting.py's STATIC URL variable from:
STATIC_URL = '/static/'
to:
STATIC_URL = 'https://hosting-****.firebaseapp.com'
Is there a way to change the path of the templates html files as well? We want to be able to quickly change both css and templates as QA tests the site.
I have stumbled upon this post that suggests to build a template loader:
def load_template_source(template_name, template_dirs=None):
try:
tpl_html = urllib2.urlopen("http://example.com")
tpl = Template(tpl_html)
return HttpResponse(tpl.render(Context({
'some_variable': 'some_val',
})))
except IOError:
raise TemplateDoesNotExist(template_name)
But being new to Django, I am not sure how to build and register a new template loader and couldn't find relevant documentation. Can someone point me to the right direction?

Django 1.8 how to create my own 404 page?

i want to create my own 404 page.
In settings.py I have added:
DEBUG = TEMPLATE_DEBUG = False
ALLOWED_HOSTS = ['*',]
In urls.py:
handler404 = 'blog.views.handler404'
In views.py:
def handler404(request):
return render(request, 'blog/404.html')
Also I have created that 404.html file.
When i start server i write:
python manage.py runserver --insecure
--insecure is to provide static files (otherwise it is nonsense). But if i go non existing page i get:
<h1>Not Found</h1><p>The requested URL /post/9/ was not found on this server.</p>
How do I solve this?
I am using Django 1.8 dunno if this changes anything
You shouldn't need anything in urls.py. Go to your root views.py and add your handler404 method there, and leave urls.py alone.
Ref: Django, creating a custom 500/404 error page
Also, I don't see your TEMPLATE_DIRS variable, i.e.
TEMPLATE_DIRS = (
'/path/to/template/files/',
'/path/to/more/template/files/'
)
Need to make sure that your templates in ../blog/.. are getting found properly. Personally I'd add that specifically as a subdirectory.

django get media directories in view or model

I have a model where I I am writing a function to upload files :
def get_upload_file_name(instance, filename):
return "my_files/{}".format(filename)
In my settings I have
MEDIA_ROOT = os.path.join(BASE_DIR, 'static')
My static structure
static
css
img
js
my_files
Here I dont want to return hardcoded my_files I want to return from setting like
{{MEDIA_ROOT}}/{}".format(filename)
or something like that...
How can I do this ?
To answer the question you actually asked, you can access your MEDIA_ROOT setting (and any other Django settings) in your views and models with:
settings.MEDIA_ROOT
As mentioned however, you probably want to read up on how media is handled in Django first.
Read about using settings in python code in the docs.
I figured it out!
You can access like this
modelName.fieldName.field.upload_to

Categories