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>
Related
I'm new to Django.
I made a URL shorter website like bitly for a test, and when users upload new URL, my program upload data to DB.
The problem is that Django doesn't reload urls.py. So if users upload their URL, data is saved in DB, but urls.py doesn't reload, so 404 shows because urls.py is not reloaded, because there are no data about new URL in urls.py.
I've searched in Google, I almost visited every website searched, but I couldn't find the answer.
How do I reload Django configurations without turning off and on the django server?
#root/url/urls.py
from django.urls import path
from django.http import HttpResponse #HttpResponse
from . import views
from . import models
urlpatterns = [
path("", views.Index),
path("urlprocess/", views.Process)
]
for i in models.Urllist.objects.all():
data = path(i.custom, lambda request: HttpResponse("<script>location.href = '{}'</script>".format(i.url)))
urlpatterns.append(data)
#views.py (Uploading Code)
def Process(request):
if request.method == "POST":
data = json.loads(request.body)
custom = data["custom"]
urllist = models.Urllist.objects.all()
for i in urllist:
if i.custom == custom:
return HttpResponse("customerror")
#upload
new = models.Urllist(url=data["url"], custom=custom)
new.save()
#reload(sys.modules[settings.ROOT_URLCONF])
return HttpResponse(custom)
else:
return HttpResponse(status="500")
Hello StackOverflow community,
I'm currently learning how to use the library Django combined with Python. However, I've ran into some issues which are somehow strange. My situation is the following. I have a project called "animals" which is the base of the Django application. My app is called "polls". Then I've defined the following views.
polls/views.py
from django.shortcuts import render
from django.http import HttpResponse
def animals(request, animal_id):
return HttpResponse("%s" % animal_id)
def index(request):
return HttpResponse('Hello world')
So far, so good. Unfortunatly I can't say the same about the urlpatterns.
polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.index,name='index'),
# Redirects to localhost:8000/polls/<animal_id>
path('<int:animal_id>/',views.animals,name='animals')
]
Whenever I want to navigate to the url "localhost:8000/polls/10/" Django reminds me of the fact, that the url is not accepted by the application and a 404 Error is thrown inside my browser. Am I missing something here?
UPDATE
I've managed to resolve the problem by fixing a rather trivial error. While the polls/urls.py was alright, the problem lay inside the animals/urls.py file. This file looked like this:
animals/urls.py
from django.conf.urls import url
from django.contrib import admin
from django.urls import include,path
urlpatterns = [
url(r'^admin/', admin.site.urls),
path('polls',include('polls.urls')),
]
As one can see, the "polls" path is not finished with a "/" sign. This indicates to Django that my desired route would be localhost:8000/polls where is any integer I add to the url. However, you have to add the slash at the end. Otherwise Django won't work as expected.
I am currently programming in the atom code editor and python 3.4.0 as well as Django 1.9. I am new to django coding.
I have managed to link the html files and the css files, but I don't know how to link the html files together.
I have tried the <a href=" "> code because normally that works (I have previous knowledge in HTML) however, everytime I click on the link, it says webpage not found.
I am trying to link base.html file to the generalq.html file.
Does anyone know any tips?
You have to put an URL in the href of your <a> element that is handled by your urls.py and views.py files:
In blog/templates/blog/base.html:
My link
In compproject/urls.py:
from django.conf.urls import include, url
urlpatterns = [
url(r'^blog/', include('blog.urls')),
]
In blog/urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^general/$', views.general, name='general'),
]
In blog/views.py:
from django.shortcuts import render
def general(request):
return render(request, 'blog/generalq.html', {})
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')
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.