Django redirect loop in form submit - django

Just to clarify, this is the first time I'm putting a django website to production.
I have a simple website in django that works locally. But when I deploy it in the production server it enters in redirect loop when I submit a form. Then the browser just tells me that a redirect loop occurred and asks to empty the cache and so on...
This problem happens in the admin. I don't know if it would happen in the frontend because it just doesn't have any form in the frontend.
Notes:
I don't have any funky middlewares.
I tested in a virtual machine with more or less the same specs of
the production server and it works fine.
The submitted data is correctly handled and saved
The rest of the website is fine
I'm using apache with wsgi in a shared host, through a .htaccess.
At this point I don't rule out the chance of a dns misconfiguration, but I already checked and looks fine.
.htaccess:
AddHandler wsgi-script .wsgi
DirectoryIndex app22.wsgi
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ app22.wsgi/$1 [QSA,PT,L]
</IfModule>
app22.wsgi:
import os, sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'BTT.settings'
path = '/home/bttmonch/apps'
if path not in sys.path:
sys.path.append(path)
path = '/home/bttmonch/apps/ENV/lib/python2.7/site-packages'
if path not in sys.path:
sys.path.append(path)
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
At this point I created a fresh new app with just the admin activated, to see if it was some codding issue and put it on the server. And the same thing happens.
I am using the same .htaccess and .wsgi files that I mentioned before.
My urls.py is just the basic:
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
I am accessing the app via test.domainname.com.
I already tried accessing it through test.domainname.com, test.domainname.com/app22.wsgi, domainname.com/test/ and domainname.com/test/app22.wsgi...

After poking around in the server I stopped getting a redirect loop. But now every time I save a form I get a 403 error. Than I clear the browser cookies and all comes back to normal, and the form data is successfully saved in the database.
At this point a just don't now what else to try...

Related

URL configuration issue with Django app using Bluehost

I'm in the process of deploying my Django app to a production server using Bluehost but keep seeing my site's 404 page. The issue seems to be my URL configuration. When I type http://www.example.com/ into my browser I receive the following :
Request URL: http://www.example.com/public_html/
^main/
^admin/
^accounts/
^media/(?P<path>.*)$
etc..
The current URL, public_html/, didn't match any of these
public_html/ is automatically added to the end of my URL I would like to eliminate the public_html/ entirely so my URL pattern will work as expected. For example
Request URL: http://www.example.com/
Which would then redirect to
Request URL: http://www.example.com/main/
How would I go about changing the default from http://www.example.com/public_html/ to http://www.example.com/ ?
My fcgi file:
AddHandler fcgid-script .fcgi
RewriteEngine on
RewriteBase /
RewriteRule ^(media/.*)$ - [L]
RewriteRule ^(adminmedia/.*)$ - [L]
RewriteCond %{REQUEST_URI} !(cgi-bin/mysite.fcgi)
RewriteRule ^(.*)$ cgi-bin/mysite.fcgi/$1 [L]
My .htaccess file:
#!/home/username/python/bin/python
import sys, os
sys.path.insert(0, "/home/username/python")
sys.path.insert(13, "/home/username/MySite")
os.environ['DJANGO_SETTINGS_MODULE'] = 'MySite.settings'
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")
Is there a possibility this could be an issue with where my files are located on my server? If anyone has experienced this kind of issue before I would greatly appreciate some advice. Thanks!
You have to define following url in your urls.py,
url(r'^$', 'views.home', name='home')
url(r'^main/$', 'views.main', name='main')
then in views.py
def home(request):
return HttpResponseRedirect('/main/')
def main(request):
#some code here.

Django Response Delay for every request

currently, I move my Django application on a production server. The problem is that each request to the server is slower by 1 second, then locallhost. (I don't mean static files. For testing I made ​​a simple VIEW, that not access the database and not contain python code only return string) I did get this values(delay 1 second) ​​of Chrome / Network/ Property - request - Waiting. Property Sending/receiving is normal (cca 1-10ms)
My .htaccess:
AuthType none
Satisfy Any
Allow from All
AddHandler fast-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /mysite.cgi/$1 [QSA,L]
My mysite.cgi:
#!/usr/bin/python
# -*- coding: utf8 -*-
import sys, os
# to suppress browser output, you should explicitly say so.
import cgitb
cgitb.enable(display=True)
# Add a custom Python path.
# Set the DJANGO_SETTINGS_MODULE environment variable.
os.environ.setdefault("DJANGO_SETTINGS_MODULE","Web.settings")
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="False")
I'm not server admin, so haven´t permission for setting Apache etc.
It is possible that the application not uses FastCGI but CGI? Or something like that?
Thanks
Problem solved by server admin, the server has not installed mod_fcgid.

How do I redirect domain.com to WWW.domain.com under Django?

How do I go about redirecting all requests for domain.com/... to www.domain.com/... with a 301 in a django site?
Obviously this can't be done in urls.py because you only get the path part of the URL in there.
I can't use mod rewrite in .htaccess, because .htaccess files do nothing under Django (I think).
I'm guessing something in middleware or apache conf?
I'm running Django on a Linux server with Plesk, using mod WSGI
The WebFaction discussion someone pointed out is correct as far as the configuration, you just have to apply it yourself rather than through a control panel.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
Put in .htaccess file, or in main Apache configuration in appropriate context. If inside of a VirtualHost in main Apache configuration, your would have ServerName be www.example.com and ServerAlias be example.com to ensure that virtual host handled both requests.
If you don't have access to any Apache configuration, if need be, it can be done using a WSGI wrapper around the Django WSGI application entry point. Something like:
import django.core.handlers.wsgi
_application = django.core.handlers.wsgi.WSGIHandler()
def application(environ, start_response):
if environ['HTTP_HOST'] != 'www.example.com':
start_response('301 Redirect', [('Location', 'http://www.example.com/'),])
return []
return _application(environ, start_response)
Fixing this up to include the URL within the site and dealing with https is left as an exercise for the reader. :-)
The PREPEND_WWW setting does just that.
There is a lightweight way to do that involving VirtualHosts and mod_alias Redirect directive. You can define two VirtualHosts, one holding the redirect and another holding the site configuration:
<VirtualHost *:80>
ServerName example.com
Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost *:80>
ServerName www.example.com
# real site configuration
</VirtualHost>
And that will do the job.
This also can be done with a middleware.
Some examples:
http://eikke.com/django-domain-redirect-middleware/
https://djangosnippets.org/snippets/510/
https://djangosnippets.org/snippets/434/
This is a better version of snippet-510:
class UrlRedirectMiddleware(object):
"""
This middleware lets you match a specific url and redirect the request to a
new url. You keep a tuple of (regex pattern, redirect) tuples on your site
settings, example:
URL_REDIRECTS = (
(r'(https?)://(www\.)?sample\.com/(.*)$', r'\1://example.com/\3'),
)
"""
def process_request(self, request):
full_url = request.build_absolute_uri()
for url_pattern, redirect in settings.URL_REDIRECTS:
match = re.match(url_pattern, full_url)
if match:
return HttpResponsePermanentRedirect(match.expand(redirect))

{% url admin:index %} generating wrong urls

My django site is served up with the following in Apache's config:
WSGIScriptAlias /studio /django/studio/bin/django.wsgi
My urls.py looks like:
urlpatterns += patterns(
'django.contrib',
(r'^admin/', include(admin.site.urls)),
(r'^accounts/login/$', 'auth.views.login'),
(r'^accounts/logout/$', 'auth.views.logout'),
)
...and yet:
[admin]
...generates a link to /admin rather than /studio/admin.
Bizarrely, the urls within the admin interface itself are fine.
I'm using:
Python 2.5.2-3
Django 1.1.1
mod_wsgi 2.5-1~lenny1
apache2 2.2.9-10+lenny6
Can anyone tell me what I'm doing wrong?
cheers,
Chris
This is a bug in Django, see:
http://code.djangoproject.com/ticket/12464
The problem is that because Apache's rewrite engine is on as a result of rewriting I need to do elsewhere in the virtual host, the SCRIPT_URL environment variable is set. But, when a request is made to /project through Apache, PATH_INFO is empty, which results in SCRIPT_NAME being incorrectly set as an empty string.
Until this bug is fixed, inserting the following RewriteRule into the Apache configuration will safely work around the problem by ensuring that PATH_INFO is never empty.
RewriteEngine On
RewriteRule ^/project$ /project/ [R]
WSGIScriptAlias /project /django/project/bin/django.wsgi
Your Django instance knows nothing about the /studio part of the URL as it is handled in WSGI. You have to manually prepend it either in templates or, better, in urls.py:
in settings.py:
BASE_URL = '/studio'
in urls.py:
r('^%s/admin/' % settings.BASE_URL, include(admin.site.urls)), ...
Then your url reversing will work as expected. You admin links work because once you are in the admin interface all links are relative.

django urlconf or .htaccess trouble

I am running my django project from subfolder of a website. Lets say the address where my project is meant to open from is.
http://example.com/myproject/
the myproject folder is root folder for my user account. In that folder i have fcgi script that starts my project. The .htaccess file in the folder contains this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ mysite.fcgi/$1 [QSA,L]
The trouble is, that at some cases, instead of redireting user to page like
http://example.com/myproject/social/someurl/
it redirects to
http://example.com/social/someurl/
which does not work. What i want to know is how to fix this problem.
Redirects in django-socialauth (github.com/uswaretech/Django-Socialauth), socialauth.views.py line 177 redirects without /myproject/, similar to the generic example above. I also use django cms2.0 in the project and it redirects user at admin auth to example.com/en/myproject/admin/, not example.com/myproject/en/admin. But that could be django cms's problem.
Is this kind of behaviour django problem and i should change it with urconf and add myproject to all urls, or should i do this with .htaccess? I found similar question, which, sadly, remains unanswered:
How to write .htaccess if django project is in subfolder and subdomain?
Alan.
It's seems that django-cms-2.0 add the locale prefix to the url using the middleware level. Very well indeed.
But what's more interesting is that they prefix all of the url using resolve('pages-root')
So, you might be able to do this in the urls.py instead...
if not settings.DEBUG:
urlpatterns += patterns('',
url(r'^myproject/$', details, {'slug':''}, name='pages-root')
)
Just make sure that you append the above urlpatterns before the cms.urls.
What if you try
RewriteRule ^(myproject/.*)$ mysite.fcgi/$1 [QSA,L]
Set the RewriteBase:
RewriteEngine On
RewriteBase /myproject/
In /urls_production.py
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^myproject/', include('urls')),
)
In /settings_production.py
from settings import *
ROOT_URLCONF = 'urls_production'
Make sure you set DJANGO_SETTINGS_MODULE to settings_production in the server environment.