Django 2 media returns error 404 (top level media folder) - django

Running Django 2.1.5 with Python 3.7.2 32-bit, Win10 localhost, no nginx etc. Cloned the repo https://github.com/axelpale/minimal-django-file-upload-example.git
Can upload files and they appear as a url link in the db and as a list item on the page but the images/files do not display on the page and return 404 in the console.
Error returned:
GET http://127.0.0.1:8001/media/documents/2019/04/07/image.jpg 404 (Not Found)
I can see the file at that location in explorer.
The code is exactly as per the repo with the addition of the following:
list.html line 14
<li><img src="{{ document.docfile.url }}" height="60px"></li>
and
urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [ path('', views.list, name='list')]
I have followed the documentation as far as I can and looked at other SO post that suggest the static pattern should go first.
It should be noted that the media folder is at the top level of the directory.
for_django_2-0
-myproject
--myproject
--media
--myapp
Also:
DEBUG = True
Have tried running with:
python manage.py runserver 8001 --insecure
and
python manage.py runserver 8001
Any help would be much appreciated.
Thanks, Jon

To answer my own question, after some more digging on another topic I found this useful video.
https://www.youtube.com/watch?v=PIvlcmnayOE&t=55s
The video explains something I missed in the other tutorials. Your static urls path needs to be in the root project urls.py not the app urls.py
myproject/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 = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [
path('admin/', admin.site.urls),
path('myapp/', include('myapp.urls'))
This now works.

Related

How can I host a Django web app on Cpanel out the public_html folder?

I am trying to host a Django web application on Cpanel.
However, my hosting service is having a main folder which is called public_html. In this folder, there is the index page. My project folder named myapp is out of the public_html folder. Whenever I run the application, it is showing the content of the index.html which is in the public_html folder instead of running the home page of my application that should be executed from this main urls.py file.
Bellow is the main urls.py content.
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url
from django.views.generic.base import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path('depenses/', include('depenses.urls', namespace='depenses')),
path('cart/', include('cart.urls', namespace='cart')),
path('orders/', include('orders.urls', namespace='orders')),
path('coupons/', include('coupons.urls', namespace='coupons')),
path('', include('shop.urls', namespace='shop')),
# path('', TemplateView.as_view(template_name='templates/index.html'), name='home'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Again my project is out of the public_html folder.
Please assist me to host my application.
This is normal behavior considering the fact that the web service will attempt to serve HTML/PHP files only.
You will need to deploy your Django app through a python interpreter like Apache Passenger or something similar that would handle and serve it.
This can be easily achieved without many configurations and hassles with the Python App feature of CloudLinux.
Therefore, I would suggest you simply find a hosting provider that provides CloudLinux's Python App feature. The deployment process via that feature is with just a few simple clicks.

Page not found error - Writing your first Django app, part 1

I have installed Django 2.2.5 in my conda environment and I'm following the Django tutorial for Writing your first Django app, part 1
I followed the steps exactly but I'm getting a Page Not Found error when I try to access the polls/ url.
My root directory structure is like this
mysite/
manage.py
db.sqlite3
urls.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
polls/
migrations/
__init__.py
admin.py
apps.py
models.py
tests.py
urls.py
views.py
And my view is like this
D:\TEMP\djangotest\mysite\polls\views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello World. You're at the polls index")
My two urls files are like this
D:\TEMP\djangotest\mysite\polls\urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
D:\TEMP\djangotest\mysite\urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
And I run the app from the environment like this
(py3.6) D:\TEMP\djangotest\mysite>python manage.py runserver
But when I go to the url indicated in the tutorial it give the 404 error - page not found from the console
October 21, 2019 - 16:23:13
Django version 2.2.5, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Not Found: /polls
[21/Oct/2019 16:23:19] "GET /polls HTTP/1.1" 404 1954
From the browser it look like
Page not found (404)
Request Method:
GET
Request URL:
http://localhost:8000/polls
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
admin/
The current path, polls, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
Your main urls file is in the wrong directory. It looks like you've created a separate urls.py in the base "mysite" directory; instead you should have edited the existing one in the "mysite/mysite" directory. The one you've created isn't being used at all.

Django React -- Deployment Error On Heroku (Page not found 404)

I'm deploying my Django React project to Heroku. Build was successful, but when I visit the site which is https://django-react-app-nba.herokuapp.com/, I'm getting django-react-app-nba.herokuapp.com/:14 GET https://django-react-app-nba.herokuapp.com/static/frontend/main.js net::ERR_ABORTED 404 (Not Found)
(Development for this project followed this tutorial https://www.valentinog.com/blog/drf/#Django_REST_with_React_Django_and_React_together)
ServerError (GET https://django-react-app-nba.herokuapp.com/static/frontend/main.js net::ERR_ABORTED 404 (Not Found))
I don't understand why Django is even looking for this URL, could anyone enlighten me?
My Project Files Path
nbavoting urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("frontend.urls")),
path("", include("teams.urls")),
path("", include("users.urls")),
]
frontend urls.py
from django.urls import path
from . import views
urlpatterns = [path("", views.index)]
frontend views.py
from django.shortcuts import render
def index(request):
return render(request, 'frontend/index.html')
My guess to the problem is that the router in the frontend is conflicting with server-side routing? (I'm using HashRouter in React)
I forgot to run "npm run build"...
You forgot to run "npm run build" :D

Django URLs management

I'm a full beginner on Django. Therefore, I'm sorry if my question is not making so much sense.
I'm studying Django tutorial - step 1. I installed properly Django and created my first Django project named 'vanilla'. The urls.py script of the vanilla project is
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
When I start Django with this 'vanilla' project and start the development server at http://127.0.0.1:8000/, I correctly see the start page (with a rocket).
In a second project that I named 'djtutorial', I created as requested in Django tutorial - step 1 a 'polls' app. As requested, I modified urls.py file in djtutorial\polls which now has following content:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
If I start the server the url http://127.0.0.1:8000/polls/ is working properly. However, if I launch the root url of the site (i.e. http://127.0.0.1:8000/), I now have a 404 error.
Why is the 'root url' of the site now hidden?
There wasn't any root URL at all. Main page informing you that your project is created properly shows up only if you don't have any view of your own added to urlpatterns. When you create any page, this welcome page stops showing up and that is expected.
If you want to show your own page on root of your website, use this in your urlpatterns:
path('', >>VIEW OR INCLUDE HERE<<),

Static Files With Django 1.6

I have spent all day and nothing works. I have seen at least 20 posts here about the same topic and they are different with different suggestions and nothing works for me.
Running Django 1.6 with Python 2.7.+
I'm trying to load the css for the polls app from the django tutorial.
project layout
Project
|-polls
|-static
|-polls
style.css
|static
here is the settings.py
STATIC_URL = '/static/'
STATIC_ROOT = '/home/bri6ko/DjangoProjects/django1.6/PoolsDjangoProject/static'
template code
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}">
urls.py
urlpatterns = patterns(...)+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
polls/urls.py
urlpatterns = patterns(....,url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/home/bri6ko/DjangoProjects/django1.6/PoolsDjangoProject/'}),)
After running: python manage.py collectstatic, everything is collected and static folder which is on root gets populated accordingly with the admin and polls folders and files.
I start the server: python manage.py runserver everything works fine except the css is not loaded
this is what i get from the Chrome console when i inspect the html
....
<link rel="stylesheet" type="text/css" href="/static/polls/style.css">
....
which looks fine but gives the following output
[16/Nov/2013 00:44:41] "GET / HTTP/1.1" 404 2141
[16/Nov/2013 00:44:45] "GET /polls/ HTTP/1.1" 200 820
[16/Nov/2013 00:44:45] "GET /static/polls/style.css HTTP/1.1" 404 1649
Any help would be appreciated. I followed everything step by step. I don't know what to do anymore
UPDATE
DEBUG=True
full urls.py
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from PoolsDjangoProject import settings
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'PoolsDjangoProject.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^polls/', include('polls.urls', namespace='polls')),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
full polls/urls.py
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(),name='results'),
url(r'^(?P<poll_id>\d+)/vote/$', 'polls.views.vote', name='votes'),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/home/bri6ko/DjangoProjects/django1.6/PoolsDjangoProject/'}),
)
And when i try to access
http://127.0.0.1:8000/static/polls/style.css
I get
Page not found (404)
'polls/style.css' could not be found
I found it necessary to restart the running server after following the steps in
https://docs.djangoproject.com/en/1.6/intro/tutorial06/#customize-your-app-s-look-and-feel
in order to pick up the newly created static directory. That step isn't listed in the tutorial. I have opened a ticket requesting its addition.
I realise this answer is not likely to help your specific case but this question comes up prominently in Google when searching for problems with adding a static directory to the example Polls app.
I ran into this problem too. My problem was that I didn't have my main app in the installed apps, whatever folder that has wsgi.py in it, that needs to be in INSTALLED_APPS.
I struggled with this problem as well.
Here's how I solved it (DEBUG=True):
After creating a project and several apps, I created a directory called "static" that sat alongside my app directories (same level as .manage.py).
I set my static URL to '/static/' in settings
I set my static root to STATIC_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), '../../static/').replace('\\','/')) (BASE_DIR = os.path.dirname(os.path.dirname(__file__)))
I set my staticfiles dirs to STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"), '/Users/username/sites/containing_dir/project_dir/static/',) (assumes OSX path)
I added + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) to my urls.py for my project
My static media is now served from http://127.0.0.1:8000/static/css/styles.css (assuming runserver command).
Comment if you need addition description!
Firstly it has to be known that Django is not responsible for serving static files on production servers. However, it does serve them when DEBUG=True during development for the sake of debugging.
For serving static files when debug=true you have to do nothing. I don't know why it is creating confusion among newbies on how to setup it. The below should help you create static files for both production and dev modes clearly
Development mode : when DEBUG=True
create your project django-admin.py startproject mysite
create your app manage.py createapp myapp
Add myapp to INSTALLED_APPS in settings.py
In myapp dir, create a folder static
In the myapp/static dir, save a file myfile.css
In settings.py, provide a valid address to STATIC_ROOT folder to store static files. It could be something like os.path.join(os.path.abspath(os.path.dirname(__file__)), "mystatic") if you want to store your collected files at mysite/mysite/mystatic.
run manage.py collectstatic; now you have to see the static file collected at the directory you mentioned above..It should also create one if its not present. You are free to put any directory.
test the url http://127.0.0.1:8000/static/myfile.css
In case if its not working yet, try restarting the site.. New files are not recognized dynamically!