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/'
Related
I have a weird edge-case where I need to use the data stored in urls.py within a view, but since the urls.py file imports the view, I am getting a circular import error when I try to import the url data into the view.
cannot import name 'url_patterns'
Does Django have any way of grabbing all the url patterns within a view that could circumvent this error? The fact that the reverse() function exists indicates that it might.
You can solve this typically (well it depends a bit), by importing the urls in your view(s) locally. Like:
# urls.py
import someapp.views
url_patterns = [
url('some_url/', someapp.views.some_view),
]
and then import the urls in the views like:
# views.py
def some_view(request):
from someapp.urls import url_patterns
# ...
# do something with urlpatterns
# return response
pass
We here thus postpone the importing of the urls.py in the views, until the view function is actually called. By that time both the views.py and urls.py are (usually) already loaded. You can however not call the view in the views.py directly, since then the import is done before the urls.py is loaded.
Note that usually you do not have to import url_patterns, and you can use reverse(..) etc. to obtain a URL that corresponds to a view function (even passing parameters into a dictionary, etc.). So I really advice to look for Django tooling to handle URLs.
Found an answer:
from django.urls import get_resolver
url_patterns = set(v[1] for k,v in get_resolver(None).reverse_dict.items())
I am trying a tutorial on Django called blog. I have the following structure:
FirstBlog|FirstBlog
settings
urls
__init__
etc
blog
templates | index.html
migrations
views.py
manage.py
The view.py has
from django.shortcuts import render
from django.shortcuts import render_to_response
from blog.models import posts
def home(request):
return render('index.html')
The urls.py has
from django.conf.urls import url
from django.conf.urls import include
from django.contrib import admin
urlpatterns = [
url(r'^blog', 'FirstBlog.blog.views.home',name='home'),
]
and I get this error:
Using the URLconf defined in FirstBlog.urls, Django tried these URL patterns, in this order: ^blog [name='home']
The current URL, , didn't match any of these.
I can't seem to get it right..
Any help would be appreciated.
Thank you,
You are requesting for / url and you have not saved any such mapping. Current mapping is for /blog . So it will work for the same url.
i.e goto the browser and request /blog
If you need it to work for / then change the urls appropriately.
within your blog app, create a urls.py file and add the following code which calls the home view.
blog/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
#url(r'^',views.home, name='home'),
]
then in your root urls file which can be found at FirstBlog/urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^blog/',include('blog.urls')), #when you visit this url, it will go into the blog application and visit the internal urls in the app
]
PS:
your templates should be in blog/templates/blog/index.html
Read this docs on templates to understand how django locates templates.
This one is to understand how urls work Urls dispatcher
You are doing this in the wrong way! Try doing that using TemplateView from class-based views, which are the current standard from django views.
Check the django documentation: https://docs.djangoproject.com/en/1.9/topics/class-based-views/
Use this at the urls.py:
from django.conf.urls import url
from django.views.generic import TemplateView
urlpatterns = [
url(r'^blog/', TemplateView.as_view(template_name="index.html")),
]
And then, create a folder called templates in the project root ( like this: https://docs.djangoproject.com/en/1.9/intro/tutorial03/#write-views-that-actually-do-something ) named index.html
Simply go to file then select Save all your project instead of save. Or use shortcut Ctrl +k s on windows. Project should be able to sync and display the code on Django interface
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)),
]
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 *
I have a html file ('search.html') with a form on it. I have saved it to ~/Django/Templates just for the sake of argument. The Django book said it doesn't matter where I save it, because the framework will find it. Anyway, I have set up a function in the views.py file to render this file. Here it is:
from django.http import HttpResponse
from django.shortcuts import render_to_response
def search(request):
return render_to_response('search.html')
I have this function called in the urls.py file as well:
urlpatterns = patterns('',
(r'^$', index),
(r'^search/$', search),
However, whenever I go to visit the page with the ~/search in the URL, I get the following:
TemplateDoesNotExist at /search/
What's the problem?
In your settings.py file there is a line...
TEMPLATE_DIRS = (...)
You want to make sure the directory containing the template is in that tuple.