django urls.py cannot process the url - python

i am creating a django app, my project name is domain_com and the application name is gallery. The project is mapped to domain.com, so that works, now when i create the urls.py with these redirects its giving me these errors
(r'^domain_com/(?P<page_name>[^/]+)/edit/$', 'domain_com.gallery.views.edit_page'),
(r'^domain_com/(?P<page_name>[^/]+)/save/$', 'domain_com.gallery.views.save_page'),
(r'^domain_com/(?P<page_name>[^/]+)/$', 'domain_com.gallery.views.view_page')
error:
Using the URLconf defined in domain_com.urls, Django tried these URL patterns, in this order:
^domain_com/(?P<page_name>[^/]+)/edit/$
^domain_com/(?P<page_name>[^/]+)/save/$
^domain_com/(?P<page_name>[^/]+)/$
The current URL, edit, didn't match any of these.
any idea where the problem is? my intial install of django worked after create the application, so i am sure its the urls.py
this is my apache config
<VirtualHost *:80>
ServerName www.domain.com
ServerAlias domain.com
DocumentRoot /var/www/www.domain.com/htdocs/
ErrorLog /var/www/www.domain.com/logs/error.log
CustomLog /var/www/www.domain.com/logs/access.log combined
SetHandler mod_python
PythonHandler django.core.handlers.modpython
PythonPath sys.path+['/var/app/virtual/']
SetEnv DJANGO_SETTINGS_MODULE domain_com.settings
SetEnv PYTHON_EGG_CACHE /tmp
<Location "/gallery/">
SetHandler None
</Location>
</VirtualHost>

You have made a complicated URL of the form http://domain.com/domain_com/page_name/edit/. Yet you're testing with the URL http://domain.com/edit. Obviously, those don't match.

after updated my answer:
try this:
(r'^/edit/(?P<page_name>\w+)$', 'gallery.views.edit_page'),
(r'^/save/(?P<page_name>\w+)$', 'gallery.views.save_page'),
(r'^/(?P<page_name>\w+)$', 'gallery.views.view_page')
While urls.py is root folder of your application.
Then if you visit:
http://domain.com/edit/page1
it should work

Set up both your main root urls to include the urls of your apps: https://docs.djangoproject.com/en/dev/topics/http/urls/#including-other-urlconfs

Related

Django CSRF Malfunction after using HTTPS

I know that this problem is occurs many times here. But none of them has working for me right now. I've been struggling in this error since I change the protocol of my app to https using apache2 and LetsEncrypt. I try the configurations in settings but it doesn't solve the problem.
# settings.py
CSRF_COOKIE_DOMAIN = ".myapp.ml"
CSRF_COOKIE_SECURE = True
CSRF_USE_SESSIONS = True
SESSION_COOKIE_SECURE = True
Ofcourse in every forms with POST method required that I have has {% csrf_token %} in there. It also shows in request data. This errors occurs in Log in and Sign Up forms.
Inside the app after I add csrf_exempt in login and signup, I use DRF and when I make requests like POST, DELETE, PUT etc... It only shows the error {"detail":"CSRF Failed: Referer checking failed - no Referer."}
Here is my apache2 configuration file:
<IfModule mod_ssl.c>
<VirtualHost *:443>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
ServerName www.myapp.ml
ServerAdmin webmaster#localhost
DocumentRoot /var/www/html
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
Alias /app /home/app/app-src/static_root
<Directory /home/app/app-src/static_root>
Require all granted
</Directory>
Alias /media /home/app/app-src/media
<Directory /home/app/app-src/media>
Require all granted
</Directory>
<Directory /home/app/app-src/Project>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIScriptAlias / /home/app/app-src/Project/wsgi.py
WSGIDaemonProcess Project python-path=/home/app/app-src python-home=/home/app/app-src/venv
WSGIProcessGroup Project
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
WSGIPassAuthorization On
SSLCertificateFile /etc/letsencrypt/live/www.myapp.ml/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/www.myapp.ml/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>
NOTE: That is only occuring when I use the HTTPS protocol.
UPDATE
I start to find the bug here and I found it on my OWN HTML FILE! I Literally forgot that one of my meta tags set the referrer to no-referrer so I just replace it with origin then everything works fine.

Images not showing over SSL on apache2 with python script

I know this question has been asked several times, but I am all out of ideas and have been reading everywhere about this.
I am running Ubuntu 17.04 and Apache 2.4.25 to host a web server. I have generated my own SSL certificate. Since doing this, I am unable to view any images over SSL. Currently, I can confirm the path is working, the file is in tact and URL is correct, as I can access this typing the http URL into my browser.
If I go to the web inspector whilst loading my site, if I click on any image it gives me a 404 error.
How do I get these images to load over SSL.
My apache2 config is:
<VirtualHost *:80>
ServerName localhost
ServerAdmin info#****.com
DocumentRoot /var/www/****.com/pay
Redirect /secure https://****.com/
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
<VirtualHost *:443>
SSLEngine On
SSLCertificateFile /etc/ssl/certs/****.com.crt
SSLCertificateKeyFile /etc/ssl/private/****.com.key
SSLCACertificateFile /etc/ssl/certs/ca-certificates.crt
SetEnv SECRET_KEY ****
SetEnv PUBLISHABLE_****
ServerAdmin info#****.com
ServerName www.****.com
DocumentRoot /var/www/****.com/pay/static
WSGIDaemonProcess webtool threads=5 python-path=/var/www/****.com/pay
WSGIScriptAlias / /var/www/****.com/pay/webtool.wsgi
EnableMMAP off
EnableSendfile off
<Directory /var/www/****.com/pay>
Options +ExecCGI
WSGIProcessGroup webtool
WSGIApplicationGroup %{GLOBAL}
WSGIScriptReloading On
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
and I have a python script running to do my routes:
import os
import stripe
import cgi
print "Context-type: text/html"
from flask import Flask, render_template, request, redirect, send_from_directory
from flask import request
from flask import json
stripe_keys = {
'secret_key': os.environ['SECRET_KEY'],
'publishable_key': os.environ['PUBLISHABLE_KEY']
}
stripe.api_key = stripe_keys['secret_key']
app = Flask(__name__, static_url_path='')
#app.route('/')
def index():
return render_template('index.html', key=stripe_keys['publishable_key'])
#app.route("/hello")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(host="127.0.0.1", port="5050")
#app.route("/charge", methods=['POST'])
def charge():
# Amount in cents
amount = 500
customer = stripe.Customer.create(
email=request.form['stripeEmail'],
source=request.form['stripeToken']
)
charge = stripe.Charge.create(
customer=customer.id,
receipt_email=request.form['stripeEmail'],
amount=amount,
currency='usd',
description='Donation'
)
return render_template('charge.html', amount=amount)
I cannot work out if I need to set a route in my python script to allow images to be fetched, or I am missing something else.
I am calling the image in my index.html file with:
with the 'img' folder being in the same location as index.html. Please help.
Your image requests are being sent to WSGI, if you want Apache to handle them, you'll have to "undo" the WSGIScriptAlias of /.
I'm not a WSGI user, but it seems like you could block this from
running conditionally by putting this in your vhost:
RewriteEngine ON
RewriteRule ^/img/ - [L]
Even though this is a no-op, it should block this part of WSGi from running.

Requested URL not found with mod_wsgi in Django

I am trying to get django to work on apache with mod_wsgi. My djang.wsgi code is:
import os, sys
sys.path.append('C:/djcode/mysite')
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
And my configuration in 'httpd' is:
Alias /static/ "C:/djcode/mysite/static/"
<Directory C:/djcode/mysite/static/>
Order deny,allow
Allow from all
</Directory>
WSGIScriptAlias / C:/djcode/mysite/apache/django.wsgi
<Directory C:/djcode/mysite/apache>
Order deny,allow
Allow from all
</Directory>
Alias /files/ "C:/djcode/mysite/files/"
<Directory C:/djcode/mysite/files/>
Order deny,allow
Allow from all
</Directory>
In the folder 'files' are files where I read data (not databases) which are used to output in templates.
The urls.py code is as follows:
urlpatterns = patterns('',
('^all/$', all),
('^(sport)/$', gen),
('^(teknology)/$', gen),
...
When I start Apache, localhost, the message is "It works!". But when I try localhost/all' or localhost/mysite or localhost/mysite/all, the browser says "The requested URL /all was not found on this server`. I can not understand where does it fail
Where is the definition or class for all? It's technically the controller. Can you post it?
This line routes it:
('^all/$', all)
But we don't know what all is.
Please make sure, you have the VirtualHost configuration correctly setup in the httpd.conf file. Try using localhost first (as the ServerName) and see if it works.

How to change DjangoBB idea of a base url?

I've setup an Apache web server with mod_wsgi, and have successfully modified the basic_project of DjangoBB to be called from Apache under the site's /forum/ subtree. The problem I have is that the WSGI app receives (correctly) URLs without the /forum/ prefix, but produces URLs in the result pages that do not have any prefix.
Example of the issue: opening http://site/forum/ brings up the start page of the DjangoBB forum; the Log In link points to http://site/account/signin/ instead of the desired http://site/forum/account/signin.
How can I make all URLs produced by the DjangoBB app to include a custom prefix (/forum/ in my case) ?
UPDATE (as requested):
The part of httpd.conf that configures the project for use under WSGI:
WSGIPythonPath /var/www/forum:/var/www/forum/xforum:/var/www/forum/venv/lib/python2.7/site-packages
WSGIScriptAlias /forum /var/www/forum/xforum/wsgi.py
<Directory /var/www/forum/xforum>
<Files wsgi.py>
Order deny,allow
Allow from all
</Files>
</Directory>
Note that, without including both the project dir (…/forum/xforum) and its parent (…/forum), the WSGI app didn't work correctly.
In settings.py of the project, the FORCE_SCRIPT_NAME should be the prefix of the project's URLs beginning with a slash (/):
In my case, it should be:
FORCE_SCRIPT_NAME = '/forum'

Why does Django not generate CSRF or Session Cookies behind a Varnish Proxy?

Running Django 1.2.5 on a Linux server with Apache2 and for some reason Django seems like it cannot store CSRF or Session cookies. Therefore when I try to login to the Django admin it gives me a CSRF verification error upon submitting the login form. Has anyone come up against this and found a solution?
I AM able to make a valid post when i try this at the url of my VPS that was provided by my host. Example: vps123.hostdomain.com/admin/ and for that domain the cookies DO get set. However, when I go to www.sitedomain.com/admin/ and try to login I get a CSRF 403 error saying the cookie is not there and when I check in my browsers cookies they are not set.
I have tried setting the following in my settings file:
SESSION_COOKIE_DOMAIN = 'www.sitedomain.com'
CSRF_COOKIE_DOMAIN = 'www.sitedomain.com'
Also tried:
SESSION_COOKIE_DOMAIN = 'vps123.hostdomain.com'
CSRF_COOKIE_DOMAIN = 'vps123.hostdomain.com'
I have 'django.middleware.csrf.CsrfViewMiddleware' added to my MIDDLEWARE_CLASSES in settings.py and there is a CSRF token in the form and it shows up in the POST.
I have cookies enabled. I have tried this on multiple browsers and machines.
There is a varnish proxy server sitting in front of www.sitedomain.com that I think may be part of the problem. Anyone with experience using proxy servers and Django may be able to shed some light on that.
My apache2 config:
NameVirtualHost *:80
<VirtualHost *:80>
ServerName www.sitedomain.com
ServerAlias www.sitedomain.com
<Location "/">
Options FollowSymLinks
SetHandler python-program
PythonInterpreter nzsite
PythonHandler django.core.handlers.modpython
PythonDebug On
PythonPath "['/var/www/django_projects', '/var/www', '/usr/lib/python2.6/dist-packages'] + sys.path"
SetEnv DJANGO_SETTINGS_MODULE project_one.settings
</Location>
<location "/phpmyadmin">
SetHandler None
</location>
</VirtualHost>
<VirtualHost *:80>
ServerName othersite.sitedomain.com
ServerAlias othersite.sitedomain.com
<Location "/">
Options FollowSymLinks
SetHandler python-program
PythonInterpreter ausite
PythonHandler django.core.handlers.modpython
PythonDebug On
PythonPath "['/var/www/django_projects', '/var/www', '/usr/lib/python2.6/dist-packages'] + sys.path"
SetEnv DJANGO_SETTINGS_MODULE project_two.settings
</Location>
<location "/phpmyadmin">
SetHandler None
</location>
</VirtualHost>
The problem was that I have a Varnish Proxy server in front of my site. Varnish was taking requests and stripping cookies from them. To fix this I had to have the company that is managing the Varnish Server add '/admin' to a list of exceptions so that cookies could be passed. Sorry I can't shed more light on how the Varnish process works.
Are you including the {{csrf_token}} in your form template?
<form autocomplete="off" method="post" action="{% url auth_login %}">{% csrf_token %}
{{form|as_p}}
<input type='submit' />
</form>
And including the middleware?
'django.middleware.csrf.CsrfViewMiddleware',
From your edit, at a guess, it might have something to do with the VirtualHost configuration in Apache (if your provider is using apache). Here is an edited version of one of my apache configurations.
<VirtualHost *:80>
ServerName www.domain.com
WSGIProcessGroup my-django-site
WSGIScriptAlias / /path-to-my-django-site/wsgi/production.wsgi
Alias /media /path-to-my-django-site/media
</VirtualHost>
It may be the case that the server name within apache has to match the domain name you are hitting the box at, along with the *_COOKIE_DOMAIN settings in your Django configuration. I'm not sure if you'll be able to change this though. Might be worth speaking to your provider if no other answers yield a win.
Are you updating your template data with the csrf info?
from django.core.context_processors import csrf
def index(request)
data = {"listitems": items}
data.updates(csrf(request))
return render_to_response('template.html', data)

Categories