I've been trying to setup an Apache (2.2.15) as a proxy with gunicorn and django (1.6.11) on a CentOS server (6.7), but I'm stuck on a problem regarding the static files. (I'm fairly new to django)
I have already looked at the great documentation that Django provides, as well as a few other stackoverflow's posts, but to no avail.
What I could check :
The problem doesn't seem to come from Django or the templates, as running the development server with 'DEBUG = False' and the option '--insecure' works fine.
It probably is a problem with the Alias and Directory block I added in my virtualhost, but I can't make sense of why it doesn't work.
Gunicorn shouldn't have any word to say in it, as it doesn't serve static files.
What my configuration looks like :
1) I got my project's static files into '/var/www/myproject/static' thanks to the 'collectstatic' command.
2) Then, I created the virtualhosts (where I think the problem is) :
(first one for the redirection to HTTPS)
<virtualhost *:80>
ServerAdmin user#domain.com
ServerName localhost
ServerSignature Off
RewriteEngine on
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R,L]
</virtualhost>
(second one for the actual work)
<virtualhost *:443>
ServerAdmin user#domain.com
ServerName localhost
ServerSignature Off
DocumentRoot /var/www/myproject
Alias /static/ "/var/www/myproject/static/"
<Directory "/var/www/myproject/static">
Order Allow,Deny
Allow from All
</Directory>
ProxyPass / http://127.0.0.1:8000/ connectiontimeout=150 timeout=300
ProxyPassReverse / http://127.0.0.1:8000/
ProxyPreserveHost On
ProxySet http://127.0.0.1:8000/ connectiontimeout=150 timeout=300
... here goes the SSL and Log configuration ...
</virtualhost>
After a service restart, my static files weren't loaded and I had a 404 error on their get. An 'httpd -S' didn't throw any error and the rest of the functionalities of the web interface are working great.
I also tried without the ending '/' for the '/static/' alias as it seemed to be a problem for some other people, tried to move the files directly under /var/www/myproject and have them accessed without an alias with the DocumentRoot...
If you want to have a look at the django settings.py (don't know if it's relevant, but some django guru could find something wrong there too) :
STATIC_ROOT = '/var/www/myproject/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(os.path.dirname(__file__),'static',),)
As well as the templates :
{% load staticfiles %}
....
<link href="{% static 'bower_components/bootstrap/dist/css/boostrap.min.css %}" rel="stylesheet">
Urls.py of the project :
from django.conf.urls import patterns, include, url
from django.shortcuts import redirect
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
url(r'^$', lambda x: redirect('/Collecte/')),
url(r'^Collecte/', include('Collecte.urls', namespace="Collecte")),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
And the urls.py of the app (named 'Collecte'):
from django.conf.urls import patterns, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from Collecte import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^Collectes/Execution/ù', views.CollExecution, name='CollExecution'),
... quite a lot of them ...
)
# Commented this line from a suggestion, was present at start
#urlpatterns += staticfiles_urlpatterns
If you feel like any file is missing for the question to be relevant, just ask for it and I'll do my best :).
Alright,
I found the answer to my question in another stackoverflow thread that had a similar configuration (but with flask instead of django).
As Ajay Gupta said, I think I had a problem in the urls.py file of the project as I had to add 'static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)' (switched from using the staticfiles app django provides to this other way).
The other problem was in the apache virtualhost configuration, as I wanted my static files to be served by apache and not gunicorn or django. I was redirecting everything to the gunicorn server, even the requests to static files. So I had to add 'ProxyPass /static/ !' so that apache serves the files.
I don't know if it's the right way to do it, but it worked for me.
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
is a helper function that works only when
debug = True
So for instance just set debug = True again, restart your server and check
What is wrong:
I have installed django-tinymce to work with text fields in the admin section of my site. The editor works good, though not as expected, because whenever I try to insert an image, link, symbol etc. - that is, whenever a pop-up is ensued - editor opens a 404 Not found window instead of actual widget form.
What I have tried:
I 've tried adding
document.domain = 'my_site.com';
to tiny_mce_popup.js. Nothing changed.
Interestingly enough, the *.htm files, which are supposed to open in pop-up windows, are stored in the directory {{ MEDIA_URL }}js/tiny_mce/themes/advanced/ (as I've mentioned, server doesn't open them). But if I try and open in browser other files from that very same directory (e.g. {{ MEDIA_URL }}js/tiny_mce/themes/advanced/editor_template.js or {{ MEDIA_URL }}js/tiny_mce/themes/advanced/img/flash.gif), everything works - the files are displayed without any error.
In addition, on local server everything works just fine - the problem is encountered only after deployment.
Code that might help identifying the problem:
Project's urls.py:
urlpatterns = patterns('',
#...
url(r'^tinymce/', include('tinymce.urls')),
#...
)
TinyMCE's urls.py:
from django.conf.urls.defaults import *
urlpatterns = patterns('tinymce.views',
url(r'^js/textareas/(?P<name>.+)/$', 'textareas_js', name='tinymce-js'),
url(r'^js/textareas/(?P<name>.+)/(?P<lang>.*)$', 'textareas_js', name='tinymce-js-lang'),
url(r'^spellchecker/$', 'spell_check'),
url(r'^flatpages_link_list/$', 'flatpages_link_list'),
url(r'^compressor/$', 'compressor', name='tinymce-compressor'),
url(r'^filebrowser/$', 'filebrowser', name='tinymce-filebrowser'),
url(r'^preview/(?P<name>.+)/$', 'preview', name='tinymce-preview'),
)
TinyMCE's settings.py:
import os
from django.conf import settings
DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG',
{'theme': "advanced", 'relative_urls': False})
USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False)
USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False)
USE_FILEBROWSER = getattr(settings, 'TINYMCE_FILEBROWSER',
'filebrowser' in settings.INSTALLED_APPS)
JS_URL = getattr(settings, 'TINYMCE_JS_URL',
'%sjs/tiny_mce/tiny_mce.js' % settings.MEDIA_URL)
JS_ROOT = getattr(settings, 'TINYMCE_JS_ROOT',
os.path.join(settings.MEDIA_ROOT, 'js/tiny_mce'))
JS_BASE_URL = JS_URL[:JS_URL.rfind('/')]
So how do I make django-tinymce's pop-ups work? Thanks in advance for your help!
EDIT: Solution found. Turns out my hosting provider didn't include htm(l) in allowed static files extensions list. Now everything's working.
The fact that it is working under the development server, but not live, leads me to think that you haven't set up the media root properly in your apache conf. The development server automatically serves your media and static files but for your live deployment you need to add the media and static aliases with the relevant path.
vhost.conf:
<VirtualHost *:80>
# Your setup for your main site url, then add the below to allow access
# to the media and static roots
Alias /media/ "/path/to/myproject/media/"
<Directory "/path/to/myproject/media/">
Order deny,allow
Allow from all
</Directory>
Alias /static/ "/path/to/myproject/static/"
<Directory "/path/to/myproject/static/">
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
I can’t log in to the django admin page. When I enter a valid username and password, it just brings up the login page again, with no error messages
This question is in the django FAQ, but I've gone over the answers there and still can't get past the initial login screen.
I'm using django 1.4 on ubuntu 12.04 with apache2 and modwsgi.
I've confirmed that I'm registering the admin in the admin.py file, made sure to syncdb after adding INSTALLED_APPS.
When I enter the wrong password I DO get an error, so my admin user is being authenticated, just not proceeding to the admin page.
I've tried both setting SESSION_COOKIE_DOMAIN to the machine's IP and None. (Confirmed that the cookie domain shows as the machine's IP in chrome)
Also, checked that the user authenticates via the shell:
>>> from django.contrib.auth import authenticate
>>> u = authenticate(username="user", password="pass")
>>> u.is_staff
True
>>> u.is_superuser
True
>>> u.is_active
True
Attempted login using IE8 and chrome canary, both results in the same return to the login screen.
Is there something else I'm missing????
settings.py
...
MIDDLEWARE_CLASSES = (
'django.middleware.gzip.GZipMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.transaction.TransactionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'django.contrib.staticfiles',
'django.contrib.gis',
'myapp.main',
)
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_AGE = 86400 # sec
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_NAME = 'DSESSIONID'
SESSION_COOKIE_SECURE = False
urls.py
from django.conf.urls.defaults import * ##UnusedWildImport
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^bin/', include('myproject.main.urls')),
(r'^layer/r(?P<layer_id>\d+)/$', "myproject.layer.views.get_result_layer"),
(r'^layer/b(?P<layer_id>\d+)/$', "myproject.layer.views.get_baseline_layer"),
(r'^layer/c(?P<layer_id>\d+)/$', "myproject.layer.views.get_candidate_layer"),
(r'^layers/$', "myproject.layer.views.get_layer_definitions"),
(r'^js/mapui.js$', "myproject.layer.views.view_mapjs"),
(r'^tilestache/config/$', "myproject.layer.views.get_tilestache_cfg"),
(r'^admin/', include(admin.site.urls)),
(r'^sites/', include("myproject.sites.urls")),
(r'^$', "myproject.layer.views.view_map"),
)
urlpatterns += staticfiles_urlpatterns()
Apache Version:
Apache/2.2.22 (Ubuntu) mod_wsgi/3.3 Python/2.7.3 configured
Apache apache2/sites-available/default:
<VirtualHost *:80>
ServerAdmin ironman#localhost
DocumentRoot /var/www/bin
LogLevel warn
WSGIDaemonProcess lbs processes=2 maximum-requests=500 threads=1
WSGIProcessGroup lbs
WSGIScriptAlias / /var/www/bin/apache/django.wsgi
Alias /static /var/www/lbs/static/
</VirtualHost>
<VirtualHost *:8080>
ServerAdmin ironman#localhost
DocumentRoot /var/www/bin
LogLevel warn
WSGIDaemonProcess tilestache processes=2 maximum-requests=500 threads=1
WSGIProcessGroup tilestache
WSGIScriptAlias / /var/www/bin/tileserver/tilestache.wsgi
</VirtualHost>
UPDATE
The admin page does proceed when using the development server via runserver so it seems like a wsgi/apache issue. Still haven't figured it out yet.
SOLUTION
The problem was that I had the settings file SESSION_ENGINE value set to 'django.contrib.sessions.backends.cache' without having the CACHE_BACKEND properly configured.
I've changed the SESSION_ENGINE to 'django.contrib.sessions.backends.db' which resolved the issue.
Steps to debug:
Make sure that your Database is synced
Double check that you have a django_session table
Try to authenticate
Do you see a record being created in the django_session table?
IF NOT
remove non-standard settings
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_AGE = 86400 # sec
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_NAME = 'DSESSIONID'
SESSION_COOKIE_SECURE = False
Make sure that your Database is synced
Double check that you have a django_session table
Try to authenticate
Do you see a record being created in the django_session table?
Let me know if this turns up any useful debug.
Sample settings file: https://github.com/fyaconiello/Django-Blank-Bare-Bones-CMS/blob/master/dbbbcms/settings.py
>>> from django.contrib.auth import authenticate
>>> u = authenticate(username="user", password="pass")
>>> u.is_staff = True
>>> u.is_superuser = True
Is there something else I'm missing?
u.is_active should be True
I had this problem. The issue is that in production I set two variables to True that allowed me to connect to the site using https.
SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE should be set to False if you are developing on localhost http. Changing these two variables to False allowed me to sign into the admin site when developing locally.
I don't believe the admin password is stored in the settings.py file. It's created when you first syncdb. I am thinking you either skipped creating the superuser or just made a typo.
Try running in terminal at your projects root.:
python django-admin.py createsuperuser
That will allow you to retype your admin login. Also seen here https://docs.djangoproject.com/en/dev/ref/django-admin/
Did you try by creating the user with :
python manage.py createsuperuser
I have the same issue when I create the db on a test machine and migrate it to the deployment server...
We had a similar issue in our app and these might help:
Use cleanup command to clear older sessions from django_sessions
Check the cookie size in firefox(firebug) or chrome developer tools. Because messaging is enabled by default in admin(django.contrib.messages.middleware.MessageMiddleware), the cookie size sometimes get larger than 4096 bytes with multiple edits and deletes. One quick test is to delete the "message" cookie and see if you can login after that.
And we actually ended up switching to nginx/uwsgi route because of this and other memory related issues with apache. Haven't seen this repeated in nginx since.
After not being able to log in myself, I saw in the comment above someone mentioned about removing non-standard settings.
Adding this to my local settings solved it for me
SESSION_COOKIE_SECURE = False
sounds like a session problem because after the post you get redirected and immediately the system has forgotten that you logged in.
try the following:
check your session backend is working.
swap it with cache backend if you use db cache backend to check if transaction middleware is messing around.
try db backend and check if there are sessions stored in the db table
I'm not exactly sure, but the problem might be with your URL configuration, concretely in these two lines:
(r'^admin/', include(admin.site.urls)),
(r'^sites/', include("myproject.sites.urls")),
A longer time ago, I had trouble with browsing the admin of my Django project because a single URL configuration overwrote a part of the admin url. It seems that Django doesn't like it when you specify a custom URL configuration that contains elements which are also part of the admin URL. In your case, you have the app django.contrib.sites enabled in your settings.py. You can access the admin panel of this app by going to http://127.0.0.1:8000/admin/sites/. It might be that your URL configuration with r'^sites/' in it overrides a part of the admin url. Try renaming this specific URL configuration or disable django.contrib.sites in INSTALLED_APPS for testing purposes.
Please note that this is just an assumption. All I know is that Django's admin panel is a bit picky about URL configurations using similar names like its own URLs. I cannot test it myself at the moment. But maybe this helps you a bit.
Check that you have at least one site to work with.
>>> from django.contrib.sites.models import Site
>>> Site.objects.count()
(0.048) SELECT COUNT(*) FROM `django_site`; args=()
1
If you see 0 here - create one.
Checking some other articles on this topic, it could be related to sys.path. Can you check and compare sys.path when running the dev server and when running WSGI.
For some details, have a look this and that article. But I would check the sys.path first, before going into the details of this article.
Make sure your database user table having following entry is true:
is_staff => True (if exit).
is_active => True .
is_superuser => True.
This is not OP's issue, but I am posting this answer in the hopes someone may have gone down the same path as I and arrived at this question as a result.
I came back to an old codebase after a year and was denied access to the admin panel despite all of the usual checks passing (user is present, nothing looks incorrect in the database, all debug modes are on, etc). Unfortunately, I had forgotten that the admin sign in page was not at the usual /admin route, but rather at an alternate route. The /admin page was a fake sign in page that always resulted in a failed sign in.
This setup was created using the app django-admin-honeypot.
For me below settings worked on localhost
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
]
SESSION_COOKIE_DOMAIN = None
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
Disclaimer: I cannot add comments yet, so I have to ask clarification here proposing a solution at the same time. Sorry for that.
Is the user logged-out immediately after logging-in? something like this issue
You can check it in many ways, I suggest to add a hook to the logout signal (you can put it in your models.py):
from django.contrib.auth.signals import user_logged_out
def alertme(sender, user, request, **kwargs):
print ("USER LOGGED OUT!") #or more sophisticate logging
user_logged_out.connect(alertme)
then try to log in and check if the message appears in your console. If it appears, then you have to check if you have a redirect or a customized template calling logout after login. Hope it helps you find the issue.
I had same problem and it was just solved after restarting server :
systemctl restart nginx
You can ensure, the created user has been flagged as Is_staff = True, I sometimes forget to flag this to allow users to login to django admin
I had a related issue where I'd try to log in and the page would hang before the socket would eventually be killed. It turned out that I was indeed being logged in, but one of the login signal processors was freezing.
Celery couldn't pass its asynchronous tasks to RabbitMQ because the RabbitMQ server wasn't able to start.
For me, I could not login to the admin page in firefox but could login in chrome.
The problem was that I had CSRF_COOKIE_PATH set in my settings.py.
Never use that. It does not not work properly on django 1.8.
What I did was to navigate manually to the url I wanted to visit.
So like: http://wildlifeapi.herokuapp.com/admin/ was returning the awful Heroku application error.
So what I did was to visit http://wildlifeapi.herokuapp.com/admin/api/animal/ and BINGO! it worked.
The funny thing is that it works well on my phone. It's probably a django redirection bug.
My issue was that My Admin Page was not loading and not working. Here is what I did:
pip uninstall django
pip install django==2.2
For more Detail Check Django Documentation.
For anyone who encountered this problem after upgrading Django, the problem could be that the signature of the authenticate function has changed at some point. If the signature doesn't match what's expected, the backend is just ignored. So make sure your custom authentication backend authenticate method looks like this:
class EmailUsernameAuthenticationBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
# ...
And NOT like this (without the request argument):
class EmailUsernameAuthenticationBackend(ModelBackend):
def authenticate(self, username=None, password=None, **kwargs):
A bit late for the party, but to me it was different and surprinsingly simpler: for whatever reason my superuser account was gone so, obviously, the solution was I had to create it again.
I'm 99% sure I had executed migrate and makemigrations a few times after having created my superuser, but go figure...
It took me about a whole hour to finally figure it out, however. None of the variables discussed here existed in my settings.py -and still don't to the present moment- (probably because it has been nearly 10 years, so things might have changed considerably), like SESSION_ENGINE, SESSION_COOKIE_DOMAIN, CACHE_BACKEND, django_session table...
Also, Django's FAQ on this subject mentions checking if my account is_active and is_staff, but unfortunately without ever mentioning how to do it.
For my case it is always the issue with SESSION_COOKIE_DOMAIN:
On local machine I set it like:
SESSION_COOKIE_DOMAIN = 'localhost'
On remote one, domain one, like:
SESSION_COOKIE_DOMAIN = 'yourdomainname.com'
In my case, I was not able to log in because I was using email in the place of username (which in my case was "admin") to try to log in. So do ensure you're using the right username and password to log in
Use some other virtual environment.it worked for me when i used conda environment.
I'm trying to redirect the Django site root to the Django admin panel, and I've mostly got it up and running. However, I've noticed that unless there's a trailing slash in the project URL, the links on the page don't include the project folder, and instead try to find the apps in the site root.
So, say I've got a project foo, and an app bar. If you visit http://server/foo/ (with a trailing slash), everything works fine, and the links on the page go to http://server/foo/bar. However, if one visits http://server/foo, the generated links go to http://server/bar instead, which generates a 404 error.
If I set the WSGIScriptAlias to point to /foo/ instead of /foo, it would give a 404 error if I navigated to /foo. I tried to force a trailing slash in the Apache conf with Redirect, but I end up generating a recursive redirect (http://server/foo//////...). I haven't yet tried using a .htaccess file, but I suspect the same thing might happen.
I tried the same thing in urls.py, however:
url(r'^$', redirect_to, {'url': '/'}), # goes to server root http://server/
url(r'^$', redirect_to, {'url': 'foo/'}), # goes to http://server/foo/foo
url(r'^$', redirect_to, {'url': '/foo/'}), # infinite redirect
I also tried simply appending a slash to all the Django urls like so:
url(r'^(.*)/', include(admin.site.urls))
But it fails to match anything at all in the project root folder (although if you navigate to the app, that seems to work OK).
I'm using Apache 2.2 with mod_wsgi, here is the configuration:
Alias /static "C:/DJANGO~1/apps/django/django/contrib"
<Directory 'C:/DJANGO~1/apps/django/django/contrib'>
Order allow,deny
Allow from all
</Directory>
WSGIScriptAlias /foo "C:/Djangostack/apps/django/scripts/django.wsgi"
<Directory 'C:/Djangostack/apps/django/scripts'>
Order allow,deny
Allow from all
</Directory>
And this is the urls.py that mostly works:
urlpatterns = patterns('',
url(r'^', include(admin.site.urls)),
)
I've made sure APPEND_SLASH is set to True, but it doesn't seem to work in the root project folder.
Try setting APPEND_SLASH to True in your settings.py. I had a similar problem and this fixed it for me. It's supposed to default to True but I had to set it explicitly.
I am deploying a Django project on apache server with mod_python in linux. I have created a directory structure like:
/var/www/html/django/demoInstall where demoInstall is my project. In the httpd.conf I have put the following code.
<Location "/django/demoInstall">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE demoInstall.settings
PythonOption django.root django/demoInstall
PythonDebug On
PythonPath "['/var/www/html/django'] + sys.path"
</Location>
It is getting me the django environment but the issue is that the urls mentioned in urls.py are not working correctly.
In my url file I have mentioned the url like:
(r'^$', views.index),
Now, in the browser I am putting the url like : http://domainname/django/demoInstall/ and I am expecting the views.index to be invoked. But I guess it is expecting the url to be only: http://domainname/ .
When I change the url mapping to:
(r'^django/demoInstall$', views.index),
it works fine. Please suggest as I do not want to change all the mappings in url config file.
Thanks in advance.
There's a fairly simple way around this using just django, without having to touch apache.
Rename your urls.py to something else, e.g. site_urls.py
Then create a new urls.py which includes that
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^django/demoInstall/', include('site_urls.py')),
)
This will ensure that all the url reversing continues to work, too.
That should be:
PythonOption django.root /django/demoInstall
Ie., must match sub URL in Location directive.
You shouldn't be using that prefix in urls.py.