I want to open a html file i.e map.html which is saved in same directories where i saved this views.py and urls.py. (django based platform)
I wrote this sample code for views.py (to load map.html) but it is not working:
from django.template import Template, Context,RequestContext
from django.http import HttpResponse
import datetime
def router_map(request):
fp = open('./map.html')
t = Template(fp.read())
fp.close()
html = t.render(Context({'router_map'}))
return HttpResponse(html)
and my urls.py is:
from django.conf.urls.defaults import *
from umit.views import router_map
urlpatterns = patterns('',
(r'^index/$', router_map),
)
The problem is, I think, that you are using the path './map.html'. This is means that Python will try and find the current directory of the program, not the same directory as the view file is in.
Lets say the Django project is in the directory /home/foo/myproject. If you cd to that directory and run python manager.py runserver, the current directory inside the application (i.e. the directory .) will be /home/foo/myproject, which is not what you want.
The easiest way to fix this is to use the full path to the file in your call to open:
fp = open('/home/foo/myproject/myapp/views/map.html')
Related
I am trying to load a value within a XML file in my project to a HTML page so that is renders in the browser. The value that I want to display is the version number of my project and it is in the format "v2.0.0". This XML file is named 'build.xml' and is contained with the 'templates/' folder in my Python-Django project. The problem I am having is that my Python code just opens the XML file when I hit the index "/" page. I want the value to be passed to the HTML.
File: myproject/urls.py
from django.urls import path
from . import views
urlpatterns = [path('', views.index, name='index')]
File: myproject/views.py
from django.http import HttpResponse
def index(request):
#return HttpResponse('Hello, welcome to the index page.')
return HttpResponse(open('templates/build.xml').read(), content_type='text/xml')
File: myproject/templates/build.xml
<version>v2.0.0</version>
First django app and am having a bit of trouble my project is laid out like this
MyProject
-dinners (python package, my app)
-views (python package)
__init__.py
dinners.py(conflict was here... why didn't I add this to the q.. sigh)
general.py
__init__.py
admin.py
models.py
tests.py
views.py
-Standard django project boilerplate
In my /views/general.py file it looks like this:
import os
import re
from django.http import HttpResponse
from django.template import Context,loader
from dinners.models import Dinner
def home(request):
first_page_dinners = Dinner.objects.all().order_by('-created_at')[:5]
t = loader.get_template('general/home.html')
c = Context({
'dinners':first_page_dinners,
})
return HttpResponse(t.render(Context()))
And in my urls.py file I have this regular expression to map to this view
url(r'^/*$','dinners.views.general.home', name="home")
However when I try to hit the home page I get this error:
Could not import dinners.views.general. Error was: No module named models
Removing the dinners.models import at the top of general.py (plus all of the model specific code) removes the error. Am I somehow importing incorrectly into the view file? Naturally I need to be able to access my models from within the view...
Thanks
UPDATE: answer I had a file dinners.py within the -views package that was conflicting
You need to put a __init__.py file in "dinners" and "views" folder to make those valid packages.
EDIT:
Also, remove that views.py file, that will create conflict with the package.
As per the docs,it expects this file in a folder named 'registration' in templates directory.I tried that ,but I am getting a templateNotFound exception.
I have configured the registration template location like
from django.conf.urls.defaults import *
urlpatterns=patterns('django.contrib.auth.views',....)
urlpatterns+=patterns('registration.views',
url(r'^register/$','register',{'template_name':'myapp/registration_form.html'},name='myapp_register'),
)
Is there some place I can configure the location for activation_email.txt template ? When I submit the registration form ,the user is created in db ,but django searches all over python path for the activation_email.txt template
Why is it that all other templates are found with out any problem while this template is not found?
Look at your TEMPLATE_DIRECTORIES setting. The template paths are relative to any of the TEMPLATE_DIRECTORIES.
If template_name is myapp/registration_form.html, then you should create a dir "myapp" in one of the TEMPLATE_DIRECTORIES, and put registration_form.html in there.
To double check TEMPLATE_DIRECTORIES, run manage.py shell and in there from django.conf import settings; print settings.TEMPLATE_DIRECTORIES.
In my django application structure is as follows:
__init__.py
__init__.pyc
models.py
tests.py
usage.rrd
views.py
views.pyc
I am trying to access the usage.rrd file in views.py as follows:
from django.http import HttpResponse
import rrdtool
def hello(request):
info = rrdtool.info('usage.rrd')
return HttpResponse(info)
but I am getting:
opening '/usage.rrd': No such file or
directory
despite being in the current directory.
The application starts from the root directory of your project. So you you need to fix your path, ('app-name/usage.rrd') .
As mentioned in thebwt's answer it's a path issue. The working directory for your django environment will not be that of you app, hence the failure to locate your file.
You will have to specify either a full path to your rrd file (not ideal) or a path relative to the working directory.
Alternatively, a common trick to deal with issues like this is to extract the directory a particular python module is in (using __file__), and using that to translate a paths (relative to the current file) to an absolute path. For example:
FILE_DIR = os.path.realpath(os.path.dirname(__file__))
rel_to_abs = lambda *x: os.path.join(FILE_DIR, *x)
In your case:
# in view.py
import os
import rrdtools
FILE_DIR = os.path.realpath(os.path.dirname(__file__))
rel_to_abs = lambda *x: os.path.join(FILE_DIR, *x)
def hello(request):
info = rrdtool.info(rel_to_abs('usage.rrd'))
return HttpResponse(info)
p.s. you might have seen this method being used in settings.py to specify paths to sqlite3 DATABASE_NAME, MEDIA_ROOT, etc. such that the absolute path is obtained at runtime rather than being hardcoded.
I am writing a GUI application using Django 1.1.1.
This is the views.py:
from django.http import HttpResponse
def mainpage(request):
f=open('pages/index.html','r').readlines()
out=''''''
for line in file:
out+=line
print out
return HttpResponse(out)
I am trying to load the contents of index.html which is inside a folder pages inside the GUI application folder.
My project's urls.py is
from django.conf.urls.defaults import *
from gui.views import *
urlpatterns = patterns('',
(r'^/$', mainpage)
)
When I run the server I get a 404 error for the root site.
How can I load the index.html file through views?
If you require just simple output of html page, this can be achieved by simply putting following into urls.py:
(r'^$', 'direct_to_template', {'template': 'index.html'})
For the root page don't use r'^/$', just r'^$', because this ^ means "start of the string after domain AND SLASH" (after 127.0.0.1/ if you run app on localhost). That's why localhost:8080// works for you.
Edit: check yours paths too. Do you have 'pages' directory in the same directory that views.py is?
Anyway: it seems that you are trying to do something bad and against Django architecture. Look here for tutorial on writing your first application in Django.
Your actual code in the view is incorrect. Here is my fixed up version:
from django.http import HttpResponse
def mainpage(request):
lines=open('loader/pages/index.html','r').readlines()
out=''''''
for line in lines:
out+=line
print out
return HttpResponse(out)
Note that in your code the line that reads from the file is:
f=open('pages/index.html','r').readlines()
You open the file and read the lines into f and then try to iterate over lines. The other change is just to get my path to the actual index file right.
You might want to read this http://docs.djangoproject.com/en/dev/howto/static-files/ if you want to serve static pages.
Got it! ;)
It seems that the mainpage function actually runs on the urls.py (as it is imported from the views.py) file so the path I must provide is gui/pages/index.html. I still had a problem, 'type object not iterable', but the following worked:
def mainpage(request):
f=open('gui/pages/index.html','r').readlines()
return HttpResponse(f)
And url pattern was r'^$' so it worked on http://localhost:8080/ itself.