How does implementing any django apps into my own project works? - python

help needed for general advice with the example on how to implement django apps.
I am trying to implement django app called django-simple-polls.
After installing the app with...
pip install ...
...adding the app in INSTALLED APPS
...the server still runs...
...migrations runs with no problem...
...being able to create basic poll from the admin...
questions starts here as I do not know how can I see the poll on the server:
1)
urlpatterns = [
...
url(r'^poll/', include('poll.urls')),
]
I am guessing polls app is installed somewhere within django so I do not have to create any additional folder/file in my project. Do I need to import a library to use the include() function? It also mean I need to run polls only in that certain url? That means 'poll.urls' already exist?
2)
Add this tags in your template file to show the poll:
{% load poll_tags %}
...
{% poll %}`
Again my guess is just to create any template folder and put as base the code above. What does "..." mean?. Where do I put the above code? How do I call that HTML file?
Is that pretty much the only way of building apps into a project?
Thanks
ps. At the moment when visiting http://127.0.0.1:8000/poll
^poll/
^admin/
^news/index/ [name='index']
^news/post/ [name='view_post']
^news/view/category [name='view_category']
The current path, poll, didn't match any of these.
But there is path called poll. :)
Following the guidance: https://github.com/applecat/django-simple-poll/blob/master/README.md
I have created the following basic template:
<!DOCTYPE html>
<html>
<head>
<title>Polls</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
{% load poll_tags %}
...
{% poll %}
</body>
</html>
I am unable to render the surveys created in the admin onto the website.

questions starts here as I do not know how can I see the poll on the server
Answer: Make sure you change your URL mapping for your poll's urls.py.
urlpatterns = [ ... url(r'^poll/', include('poll.urls')), ]
This should be added to your project's urls.py
Again my guess is just to create any template folder and put as base the code above. What does "..." mean?. Where do I put the above code? How do I call that HTML file?
If you've set your templates folder in your settings.py you can create another folder named poll then you put your templates there. Then on your views you do.
from django.shortcuts import render
def index(request):
return render(request, 'poll/yourtemplatename.html')

Related

Trying to load a simple html in Django but it appears GET /homepage/ HTTP/1.1" 500 145

I did the Tutorial for the polling app on the official Django web page and everything worked out fine. Since I already have some HTML from my old website I wanted to reuse some of that. I decided to create an app called "homepage" for the main page you get when you visit the page (if this is bad practice, let me know). Since the main page is more or less just some introductory text and a navigation menu without any fancy functionality I did not create a DB (models) in this case. Furthermore I was sure that Django is able to simply deliver some plain static html without a database provided.
The urls.py in the hompage app folder looks like:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index1, name='index1'),]
and the view.py like this
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
Everything works out fine. As soon as I try to load a html file (here a simple one just to check if it works) I get the error message. The new view.py looks like in the tutorial suggested:
def index(request):
latest_question_list = 'Hallo'
context = {'latest_question_list': latest_question_list}
return render(request, 'homepage/index.html', context)
The folder structure is like suggested in the tutorial:
myproject_dir/myproject
myproject_dir/homepage/templates/hompage/index.html
The html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My test page</title>
</head>
<body>
<p>This is my page</p>
<p>{{latest_question_list}}</p>
</body>
</html>
Again, it works out fine with the poll app, which I have still working in the same project folder. This leaves me pretty confused and I'm looking forward to get some input.
Set the default path in your project's urls.py in urlpatterns list.
from django.urls import path,include
urlpatterns=[
path('',include('homepage.urls'))
]
Then its next route will be decided through your app's urls.py that is homepage.

Download File From Another Directory In Flask

Im New In Flask . I'm try to make download list of /var/ directory files but
i can't find any way to make this link .
any file could be in this directory so tempfile could solve this problem .
i don't know the file so i can't copy file in flask directory ,
could any one tell me how can i make download link for file like this ?
I've never used flask, but have some experience with Django.
From quickly looking at the flask docs (rendering_templates) you would have to pass a context variable to the rendering function, then add it to the jinja template.
I would also suggest designating a different folder to place downloads, as giving users access to your /var/ folder can pose a security concern.
See below:
import os
from flask import Flask, render_template
app = Flask(__name__)
dloads_dir = '/var/www/mysite/downloads/'
dloads = os.listdir(dloads_dir).sort()
dloads_src = ['/downloads/{}'.format(i) for i in dloads]
#app.route('/Downloads')
def list_downloads():
return render_template('downloads.html', dloads=dloads, dloads_src=dloads_src)
Then in the html (should I say Jinja2) template:
<!doctype html>
<title>Hello from Flask</title>
{% for file in dloads %}
<a href="{{ dloads_src[loop.index0] }}" download>{{ file }}</a>
{% endfor %}
</html>
Here's where I found the loop.index method
(1) Edit: Fixed my bad html

Where to put REST API in Django

Here is a quote from Two Scoops of Django: Best Practices For Django 1.6:
In the past, we placed all API view code into a dedicated Django app
called api or apiv1, with custom logic in some of the REST views,
serializers, and more. In theory it’s a pretty good approach, but in
practice it means we have logic for a particular app in more than just
one location.
Our current approach is to lean on URL configuration. When building a
project-wide API we write the REST views in the views.py modules, wire
them into a URLConf called something like core/api.py or
core/apiv1.py and include that from the project root's urls.py
module. This means that we might have something like the following
code:
# core/api.py
""" Called from the project root's urls.py URLConf thus:
url(r" ˆ api/", include("core.api"), namespace="api"),
"""
from django.conf.urls.defaults import patterns, url
from flavors import views as flavor_views
from users import views as user_views
urlpatterns = patterns("",
# {% url "api:flavors" %}
url(
regex=r" ˆ flavors/ $ ",
view=flavor_views.FlavorCreateReadView.as_view(),
name="flavors"
),
# {% url "api:flavors" flavor.slug %}
url(
regex=r" ˆ flavors/(?P<slug>[-\w]+)/ $ ",
view=flavor_views.FlavorReadUpdateDeleteView.as_view(),
name="flavors"
),
# {% url "api:users" %}
url(
regex=r" ˆ users/ $ ",
view=user_views.UserCreateReadView.as_view(),
name="users"
),
# {% url "api:users" user.slug %}
url(
regex=r" ˆ users/(?P<slug>[-\w]+)/ $ ",
view=user_views.UserReadUpdateDeleteView.as_view(),
name="users"
),
)
But I don't understand where to put core/api.py. Is this a separate Django app called core? Where api.py should sit?
It means create the file you have as core/api.py (along with an empty core/__init__.py file) and then add the line url(r" ˆ api/", include("core.api"), namespace="api") to the root urls.py file of your project.
You don't have to call it core/api.py, that is just a suggestion from the authors
what does we write the REST views in the views.py modules mean?
It means what you've done, for each of the Django apps in your project, such as flavors, users they will have a views.py (or views/*.py) in them where you'd put the code for both the API and non-API views. (this is just a sane naming convention, nothing more... Django relies on the urlpatterns to tell it how to connect url routes to view code)
It's great to build up stuff like this from scratch as a way to learn Django. If you're doing a serious REST API project have a look at Django REST framework.

How can i serve html files from diff directory in django

I need to make an app where i have the ready made standalone html templates avaialbe in my
app/ready_templates/template1
Now i have made an view where i display the name , thumbnail of that template to show to users
But there is demo link there which i want tthem to see the whole template.
basically if they click on demo then i want to redirect them to
template1/index.html so they can see all the templates images , js etc without linking anything to django views
So your requirement seems pretty straightforward. You can do this using the static files feature in Django. Basically whenever you have a bunch of static content like html, css, js images you put it in a folder in your app called static. For example the admin app that ships with Django has all it's static content in django/contrib/admin/static. Then you could place something simple like the below into your django template to link to the static content. You of course don't have to hard code each name like template1 you could have it dynamically generated in your django template.
{% load static from staticfiles %}
<a href="{% static "template1/index.html" %}" />template1</a>

Python template help

I'm using App Engine's web-app templating system (similar if not identical to django)
Normally I render templates from my static directory /templates/ as
follows in my main handler:
dirname = os.path.dirname(__file__)
template_file = os.path.join(dirname, os.path.join('templates', template_name))
output = template.render(template_file,template_values)
self.response.out.write(output)
For my current app, I want to render a template contained in a
string. I'm using the following code:
t = template.Template(template_string)
c = template.Context(template_values)
output = t.render(c)
self.response.out.write(output)
It renders the template, but not the "include" tags contained within
the string. For example, the string template
"hello world {% include 'helloworld.html' %}"
renders "hello world" but does not render the contents of
'helloworld.html'.
I'm guessing that this has something to do with the string not being
in the same directory as 'helloworld.html', but I'm not sure how to
specify that the include tags should look in '/templates/*'
Any help would be appreciated,
Arjun
The webapp framework uses Django 0.9.6 templates. If you're loading templates from a string as you describe above, you need to configure the template loader so it can find dependencies loaded from files. Here's how webapp configures them.
{% include 'dirname/helloworld.html' %}
should work!

Categories