I am stuck at Django undefined main_page - django

I am learning Django and doing the job of setting everything up.
I have my views.py in jangoTest/first/views.py
in which I defined:
def main_page(request):
output = '''
<html>
.....
</html>
return HttpResponse(output)
I have my urls.py in jangoTest/urls.py
in which I wrote:
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',(r'^$', main_page),)
but the main_page turns out 'undefined' and I am stuck at this point.
Any one knows how to fix this problem???
Thanks a lot!

Aren't you missing the import in the urls.py file?
from views import *

Related

How to go from one page to another in django

I'm new to Django and python (infact my first language which I've only been learning for 3 months)
I'm creating this website using Django and I'm not able to go from one page to another using the href tag. it throws at me a 404 error saying "current path didn't match any of these"
This is my code
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import off
# Create your views here.
def homepage(request):
return render(request=request,
template_name='main/home.html',
context={'toll' : off.objects.all})
def secondpage(request):
return render(request = request,
template_name = 'main/next.html')
main/urls.py
from django.urls import path
from . import views
app_name = 'main'
urlpatterns = [
path('',views.homepage,name='homepage'),
path('',views.secondpage,name='secondpage')
]
templates/mains/home.html
<div class="topnav">
Link
Link
Link
</div>
I also request the helper to simply it for me as I wouldn't be able to handle complex and advanced python terminology
Thanks In Advance From a Friend
Arvind
I think you should read this to start with Django.

Could not parse the remainder: '-save' from 'waypoints-save'

I am trying a simple app in geodjango by following http://invisibleroads.com/tutorials/geodjango-googlemaps-build.html.
My view function is
# Import django modules
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.loader import render_to_string
# Import system modules
import json
# Import custom modules
from waypoints.models import Waypoint
def save(request):
'Save waypoints'
for waypointString in request.POST.get('waypointsPayload', '').splitlines():
waypointID, waypointX, waypointY = waypointString.split()
waypoint = Waypoint.objects.get(id=int(waypointID))
waypoint.geometry.set_x(float(waypointX))
waypoint.geometry.set_y(float(waypointY))
waypoint.save()
return HttpResponse(simplejson.dumps(dict(isOk=1)), mimetype='application/json')
And urls.py is
from django.conf.urls import patterns, include, url
urlpatterns = patterns('waypoints.views',
url(r'^$', 'index', name='waypoints-index'),
url(r'^save$', 'save', name='waypoints-save'),
)
It is showing an error http://dpaste.com/3EJVX0G
Template index.html is here http://pastebin.com/125Dm6Bz
Please help me.I am new to django.
The parameter to the {% url %} tag must always be in quotes if it's a literal string (this has been the case since version 1.5, which is quite a long time).
The one that's causing the error is this:
$.post("{% url waypoints-save %}"
which should be:
$.post("{% url "waypoints-save" %}"
but you make the same mistake several times in that template.

How can i redirect from one domain to another in django app?

Normally i would do it with .htaccess but django doesn't have it.
So what is the best way and what is the code for it to redirect from www.olddomain.com to www.newdomain.com?
NOTE: we are not using Apache, but Gunicorn
thanx!
The best way to do this is still with your web server rather than Django. This will be much quicker and more efficient than doing it with Django.
Check out this question for more info.
UPDATE
If you really want to do it within django then edit your url conf file (which manages django's url dispatcher) to include the following at the top -
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
(r'^.*$', redirect_to, {'url': 'http://www.newdomain.com'}),
)
For more info check out the documentation.
import urlparse
from django.http import HttpResponseRedirect
domain = request.GET['domain']
destination = reverse('variable_response',args=['Successful'])
full_address = urlparse.urljoin(domain, destination)
return HttpResponseRedirect(full_address)
i had the same problem so i wrote this and it worked perfectly for me, maybe someone else needs it too:
urlpatterns += [ # redirect to media server with same path
url(r'^media/', redirectMedia),
]
and using this function to redirect:
from urllib.request import urlopen
from django.http import HttpResponse
def redirectMedia(request):
x = urlopen("http://www.newdomain.com" + request.path)
return HttpResponse(x.read())
enjoy it!
For Django >= 2.0 , the easier solution is to use RedirectView
For example in urls.py :
from django.views.generic.base import RedirectView
urlpatterns = [
path('my_ext_uri', RedirectView.as_view(url='https://YOUR_EXTERNAL_URL')),
]
[Side note]
As mentioned in Aidan's answer , it would be better to redirect requests which will be handled by different services at web server gateway, rather than at (Python/Django) application server.
I ended up doing it using heroku and spinning up 1 web dyno (which is free).
#views.py
def redirect(request):
return render_to_response('redirect.html')
#redirect.html
<html>
<head>
<title>Blah</title>
<meta http-equiv="refresh" content="1;url=http://www.example.com">
</head>
<body>
<p>
Redirecting to our main site. If you're not redirected within a couple of seconds, click here:<br />
example.com
</p>
</body>
</html>
Simple as that. Can find the same example here.
An alternative to catherine answer, updated to Python 3 is:
from django.contrib.sites.shortcuts import get_current_site
from urllib.parse import urljoin
from django.http import HttpResponseRedirect
NEW_DOMAIN = 'www.newdomain.com'
Put in each view:
def myView(request, my_id):
if request.META['HTTP_HOST'] != NEW_DOMAIN:
# remove the args if not needed
destination = reverse('url_tag', args=[my_id])
full_address = urljoin(DOMAIN, str(destination))
return HttpResponseRedirect(full_address)
# your view here
The url_tag is the one defined in urlpatterns.
I ended with simple solution:
return HttpResponse(f"<script>location.replace('https://example.com/');</script>")
It works if user don't disable scripts in webbrowser
You could do it simply adding the redirect in the value 'urlpattens' found in 'urls.py'. Hope it helps. The reference is source.
from django.shortcuts import redirect
urlpatterns = [
path('old-path/', lambda request: redirect('new-path/', permanent=False)),
]

Django.views is missing why? No module named django.views

I have a problem with django.views
My Code is
template
<!doctype html>
<html>
<h1>{{userName}} twoje wycieczki : </h1>
Dodaj wycieczke>>
</html>
basic html template with url tag.
my views.py
def tripList(request):
user = request.user
print user.username
tList = Trip.objects.filter(userId = user.id)
return render_to_response('tripList.html',{'userName' : user.username}, context_instance = RequestContext(request))
also urls.py
from django.conf.urls import patterns, url
from views import *
urlpatterns = patterns('',
url(r'^createTrip/$', createTrip, name = 'createTrip'),)
but i get error
No module named django.views
Exception Location: /var/src/Django-1.4.2/django/utils/importlib.py
in import_module, line 35
And I don't know what is wrong because i have included django.views in settings.py and in my python console also django.views can be imported so there is django.views
I have no idea what's wrong. I have other views with url tag but there was no bug like that.
Maybe someone have simple problem. Thank's in advance.
What is the name of your project, and where is your views.py is located? Usually, you do not have such a line while importing your views:
from views import *
If you are importing views within your project, please use the name of the project as a prefix. If you have an application in its own folder, say trip, you need to import its view file as
from trip.views import *
My problem was laying in configuration of django. You have file settings.py and my problem was with configuration of MEDIA_* variables configuration. You have to remember that MEDIA_ROOT should be absolute path to files in yor file system, MEDIA_URL that is mapping your media file access, and STATIC_URL also should be filled. This is my configuration. When I properly filled it problem dissapeared. :) If you have any more question write.
MEDIA_ROOT = 'myAbsolutePath\media\\'
MEDIA_URL = '/media/'
STATIC_URL='/static/'

Django response redirect on variable url

I'm on a page with a variable url /emails/edit/32/, and I want to update the form and refresh the page...how do I issue an HttpResponseRedirect to the current page, which has a variable extension?
My urls.py is:
urlpatterns = patterns('',
(r'^emails/edit/$', 'email_edit'), # this is the page it is re-directing to
(r'^emails/edit/(?P<email_id>\d+)/$', 'emails_single'),
)
And my views.py is:
def emails_single(request, email_id):
...(stuff)...
Email.objects.filter(id=request.POST['id']).update(email=request.POST['email'])
return HttpResponseRedirect(reverse('emails_single',args=[email_id]))
Update: what it is doing is just chopping off the ending of the URL (even when using the reverse examples). For example: http://127.0.0.1:8000/emails/edit/42/ --> http://127.0.0.1:8000/emails/edit/
from django.core.urlresolvers import reverse
return HttpResponseRedirect(reverse('emails_single', args=[email_id]))
reverse()
from django.core.urlresolvers import reverse
def myview(request):
return HttpResponseRedirect(reverse('urlname', args=[1945]))