Uploading files POST urls raise 404 when deploy - django

I'm deploying a django app on a host with apache and cPanel. I think I did all the steps that django needs to deploy. Everything works fine except dome admin posts urls.
When I'm sending a form via post from the admin site, and one of its fields is a File that will be uploaded to a directory, the server responses me 404. Some info:
Python 3.5, Django 1.11.9
Error: 404 Not Found
When: sending any post form containing a Choose File field, even if the file isn't mandatory.
The forms without files in their fields work fine. In production everything works perfect.
I have a symlink in the public_html folder to my media and static folders.
This error only shows in the admin page. I can upload file from the site without any problem
This is my code:
urls.py
urlpatterns = i18n_patterns(
url(r'^admin/', admin.site.urls),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^', include('myapp.urls')),
prefix_default_language=False)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
This is my first time hosting a website, so, sorry if I'm asking a dummy question, but I couldn't find any solution, even here. Also, sorry for my English. Thanks for the future answers
EDIT
My non-admin forms work perfect. The problem is in the admin page. I edited my old question with the changes in bold

It can be web server problem. Check your cPanel settings
May be something wrong with your wsgi file location
Check up some tutorial for more info.

In case you are serving media files using django's static file server, the urlpatterns variable in your project's base urls.py file should be assigned in a specific order so that the i18n_patterns(...) assignment places before the static(...) url.
you should do it like so:
urlpatterns = i18n_patterns(
url(r'^admin/', admin.site.urls),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^', include('myapp.urls')),
prefix_default_language=False)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Related

Can I deploy a Django App if there is no "" (empty) url?

I'm trying to deploy a Django App with railways for the first time and I was wondering where exactly will be my landing page. So basically my urls.py looks something like this:
path('home/', views.home, name="home"),
path('blogposts/', views.blogposts, name="blogposts"),
path('posts/', views.posts, name="posts"),
After deploying my Blog website, let's say with the domain 12345xxx.com, where will I land?
You will get an error if you don't include a folder in the URL, as the URL patten won't be matched and the existance of non-admin URLs stops the default django page from showing. This will be either a 404 error or a 'Django tried these URL patterns, in this order:' type error if you have DEBUG=True on in settings.
Note that you don't have to provide a path (the path can be an empty string), and views can have multiple paths. In this case, perhaps
path('', views.home, name="home"),
path('home/', views.home, name="home_folder"),
path('blogposts/', views.blogposts, name="blogposts"),
path('posts/', views.posts, name="posts"),
would avoid an error.

Django Admin - FORCE_SCRIPT_NAME is appended twice to URL when POSTing

I have deployed Django to a sub directory (I don't have full control over the server so can't change the way it's deployed).
I added to my settings:
FORCE_SCRIPT_NAME = '/hub06'
STATIC_URL = FORCE_SCRIPT_NAME + '/static/'
Now when I go to /admin/hub06, it's working properly, I can login and browse all admin pages. As soon as I do a POST request though (adding a new model), the URL gets corrupted.
For example, when editing /hub06/admin/myapp/car/1
When I submit the form, it redirects to /hub06/hub06/admin/myapp/car/
So it adds script name twice. This is only for POST requests in Django admin.
Is this a linux host? is it running apache, nginx? It all depends on how your web server is configured.
If you really must have a url prefix like /hub06/ then you will need to update any settings in settings.py that return a url such as LOGIN_URL, STATIC_URL, LOGIN_REDIRECT_URL etc to contain the prefix.
I don't think you need to use FORCE_SCRIPT_NAME. Comment that bit out in the settings.py and update urls.py to add the following for example:
from django.conf.urls import patterns, include, url
from django.contrib.auth.views import login
from django.contrib import admin
admin.autodiscover()
urlpatterns2 = patterns('',
url(r'^$', 'yourapp.views.home', name='Home'),
url(r'^admin/', include(admin.site.urls)),
)
urlpatterns = patterns('',
url(r'^hub06/', include(urlpatterns2)),
)
Let me know how you go.
This was the solution:
# NB - this setting is required to make the app work correctly when running
# via ProxyPass from Apache. Otherwise CSRF checks and some redirects will not
# work.
USE_X_FORWARDED_HOST = True

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!

My DJango app is responding to /static urls

Update
I figured out what was causing the stylesheets to become invisible, though I don't quite understand it all. I set DEBUG=False in settings.py to test the error handling as described in the tutorial. Somehow setting debug to false causes the static files not to be locatable. I will look further in the configs to see if I can get a clear understanding why. Until then, please feel free to answer or comment with additional info. I am still learning!
Update
I'm going through a DJango tutorial from here and I hit a roadblock. I'm up to tutorial 3 where they explain how to refactor your urls.py file when I try loading up the admin site to make sure I haven't broken it. Sure enough it looked all wierd because it was missing the stylesheets. Stylesheets are pulled from here:
http://127.0.0.1:8000/static/admin/css/base.css
When I hit that link in my browser I get the custom 404 page I configured for my app. The stylesheets were working prior but I'm not sure which change broken them. I went through my urls.py file and reverted all of the polls specific url configs to no avail. Here's my current urls.py under hellodjango (the name of my project.)
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from django.http import HttpResponse
admin.autodiscover()
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls')),
url(r'^admin/', include(admin.site.urls)),
)
def page_not_found(request, template_name='404.html'):
return HttpResponse("Could not find the resource you asked for...")
handler404 = 'hellodjango.urls.page_not_found'
and here's the urls.py under my polls directory:
from django.conf.urls import patterns, url
# Uncomment the next two lines to enable the admin:
urlpatterns = patterns('polls.views',
url(r'^$', 'index'),
url(r'^(?P<poll_id>\d+)/$', 'detail'),
url(r'^(?P<poll_id>\d+)/results/$', 'results'),
url(r'^(?P<poll_id>\d+)/vote/$', 'vote'),
)
Help?
It looks like you don't have a URL pattern for /static. As such, the static/admin/css/base.css URL doesn't match any pattern, and so you get a 404. Try something like this:
from django.conf.urls.static import static
# ...
urlpatterns = patterns('',
# ...
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT}),
# ...
This should work for you -- go to /static/foo.css, and you should see your CSS.
It's worth noting that this is discouraged in a production environment. For your tutorial app, though, it'll work.
The staticfiles app provides a custom runserver management command that automatically serves the static files, are you sure you have the following in your settings?
INSTALLED_APPS = (
# ...
'django.contrib.staticfiles',
)
In production, you'll use the collectstatic management command that finds all of the static media and dumps it into STATIC_ROOT (this is the only purpose for this setting - it isn't used or needed during development).
Glad you figured it out. Here's why it works like this.
django.contrib.staticfiles overrides the runserver management command so that the static files are served automatically. To remind people that they shouldn't be using django to serve static files, this only happens when DEBUG = True, as you found out.
The documentation of the overridden management command explains that you can use the --insecure flag to make this work no matter the state of the DEBUG setting.

Django - uploaded images can not be retrieved

I am exploring file/images uploads in Django. I have a model with Photo class which has thumb ImageField. I uploaded thumb with admin panel and I made template which just gives <img src='{{photo.thumb.url}}' />. Unfortunately I don't get any images and when I try to get direct link it says "page not found". It seems that django either does not move them to media_url or maybe it has no permission to access it? I wonder what can I do to fix it.
Thanks a lot beforehand.
PS: Running django on dev server with sqlite db.
The development server by default doesn't serve static files (see the documentation). You'll need to add the following code to the bottom of your urls.py to enable static file serving:
from django.conf import settings
if settings.DEBUG:
urlpatterns += patterns('',
(r'%s(?P<path>.*)' % settings.MEDIA_URL[1:], 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
That should sort you out.