Sriram
Sriram

Reputation: 1190

What may be the problem (Django views)...?

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?

Upvotes: 0

Views: 213

Answers (4)

Aleksei Potov
Aleksei Potov

Reputation: 1578

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'})

Upvotes: 3

Sriram
Sriram

Reputation: 1190

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.

Upvotes: 0

Daniel Hernik
Daniel Hernik

Reputation: 321

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.

Upvotes: 1

Johan
Johan

Reputation: 1200

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.

Upvotes: 0

Related Questions