Django not serving HTML table in template (word counter web app) - python

Summary:
Django is not rendering a basic 2 column by 11 row HTML table containing the top 10 most commonly used words in a large text file (Alice and Wonderland which is a public domain work). But right now the table is empty.
Details:
The table currently rendering on the web page looks like this, see here on imgur. In that pic, notice the bottom right corner, the table is empty.
The fully populated word counter table and its contents render when a web user navigates to http://127.0.0.1:8000/counters. See here on imgur.
However the problem in the second pic is that the blog post 'lorem ipsum' content is empty.
Here is my parent top level urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
# path('', include('mortems.urls')),
path('', include('redactors.urls')),
path('', include('posts.urls')),
path('', include('counters.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Here is my counters app’s views.py:
from django.shortcuts import render
from collections import Counter
import re
from nltk.corpus import stopwords
def counters(request, text=""):
"""
This function processes the top 10 most common words in a text file and then renders them.
"""
text = open("counters/Alice.txt", "r").read().lower()
stoplist = stopwords.words('english')
stoplist.extend(["said","gutenberg", "could", "would",])
clean = []
for word in re.split(r"\W+",text):
if word not in stoplist:
clean.append(word)
top_10 = Counter(clean).most_common(10)
return render(request, 'alls/landings.html', {'top_10': top_10})
Here is my counters app’s urls.py:
from django.urls import path, include
from . import views
urlpatterns = [
path('counters', views.counters, name='counters'),
]
Take note of the first argument inside the path function. That is the problem because now web visitors see the table when they navigate to 127.0.0.1:8000/counters but I am trying to make Django serve the table when the user navigates to 127.0.0.1:8000/or 127.0.0.1:8000/home. So when I change that first ‘counters’ argument to ‘home’ or ‘’ (leaving it blank) then the table doesn’t render at all.
To conclude, what I am trying to do is have Django serve the counters function and pass in the top_ten dictionary when rendering the alls/landings.html template when the website visitor navigates to either http://127.0.0.1:8000/home or http://127.0.0.1:8000/. That is what I am trying to accomplish. But instead right now to see the table, the user needs to visit http://127.0.0.1:8000/counters where the blog post content is absent.
There is no traceback in my Django server logs, so I don’t have very many Google search terms to work with.
By the way, for what it is worth, here is my abridged (reduced) HTML table as it appears inside my templates/alls/landings.html:
<h1>Counting the words!</h1>
This should only show inside landing.html
<div class="">
<table>
<tr><th>Word</th> <th>Quantity</th></tr>
{% for word, count in top_10 %}
<tr> <td>{{word}} </td><td>{{count}} </td></tr>
{% endfor %}
</table>
</div>
Here is a complete static snapshot of my full source code on GitHub.

I think the way you have designed your top level urls is the problem. If you want the user to redirect to your counter view as soon as he/she visits the homepage, you need to change the parent urls.py to something like this:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
# path('', include('mortems.urls')),
path('redactors', include('redactors.urls')),
path('posts', include('posts.urls')),
path('', include('counters.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The problem in your version is that as soon as a user visits homepage, he is directed towards redactors.urls as that is the first match found for the homepage url.
Next, you will need to change the counters.urls to:
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.counters, name='counters'),
]
This will redirect the user directly towards the counter view when he/she visits your web homepage.
Alternatively, if you want the counter view to be served on http://127.0.0.1:8000/home, then you can change the parent urls.py to:
path('home/', include('counters.urls')),

Eureka! It’s working!
Since last time, counters/views.py has been rearranged. The functions contained inside that view have been moved into the posts/views.py. Even the top_word_counts function has been moved into a new file at posts/utils.py. Here is a screenshot on imgur showing the table with the most commonly appearing words in Alice.txt (bottom left corner): https://imgur.com/XTh1FGL
You might notice traces of new functionality. For example not only does my app count the contents of Alice.txt but now the app also counts the most commonly appearing words inside the blog posts (right now lorem ipsum placeholder content).
With all of those changes in mind, here is my working posts/views.py:
import operator
from django.shortcuts import redirect, render, get_object_or_404
from posts.models import Posts
from .utils import top_word_counts
def posts(request):
posts = Posts.objects.all().order_by('-pub_date')
context = {'posts':posts}
post_string = ''
for post in posts:
post_string += post.body
post_words = top_word_counts(post_string.lower())
alice_words = top_word_counts(
open("counters/Alice.txt", "r").read().lower())
context.update({
'post_words': post_words,
'alice_words': alice_words
})
return render(request, 'alls/landings.html', context)
Here is my new posts/utils.py:
import re
from collections import Counter
from nltk.corpus import stopwords
def top_word_counts(text):
# text = open("counters/Alice.txt", "r").read().lower()
stoplist = stopwords.words('english')
stoplist.extend(["said", "gutenberg", "could", "would", ])
clean = []
for word in re.split(r"\W+", text):
if word not in stoplist:
clean.append(word)
top_10 = Counter(clean).most_common(10)
return top_10

Related

Django URL translation dependent on URL prefix language code

I am trying to internationalize a Django dictionary application using the Django translation system. I have successfully translated most of the content on the site but I am having problems translating URL patterns, with the exception of the admin page.
My goal is to change the language of both content and URL based on prefix language code in the URL. For example:
www.example.com/en/dictionary/define // (content in English)
www.example.com/it/dizionario/definisci // (content in Italian)
www.example.com/fr/dictionnaire/définis // (content in French)
...
I checked the Django documentation on this (https://docs.djangoproject.com/en/3.1/topics/i18n/translation/#translating-url-patterns) but found it quite vague and could not really understand it.
project-level urls.py:
from django.conf.urls.i18n import i18n_patterns
from django.utils.translation import gettext_lazy as _
from dictionary import views as dictionary_views
urlpatterns = [
path('admin/', admin.site.urls),
]
dictionary_patterns = ([
path('', dictionary_views.index, name='index'),
path(_('define/'), dictionary_views.define, name='define'),
path(_('define/<slug:headword_slug>'), dictionary_views.headword, name='headword'),
], 'dictionary')
urlpatterns += i18n_patterns(
path(_('dictionary/'), include(dictionary_patterns, namespace='dictionary')),
)
As for app-specific urls.py, I have no clue on what to do there. Should I import the dictionary_patterns variable from above and add it to the app's urlpatterns list? Should I delete the app's urls.py file altogether?
Can anybody help?
Just try to add import include in the urlpatterns like
In the project/urls.py
from django.conf.urls import include
path('en/dictionary/',include('app URL here with extension.url'),
path('it/dizionario/',include('app URL here with extension.url'),
path('fr/dictionnaire/',include('app URL here with extension.url'),
In the Appname/urls.py
urlpatterns = [
url(r'^define$/',views.name of view,name=''),
url(r'^definisci/$',views.name of view,name=''),
url(r'^définis/$',views.name of view,name=''),
Check this out:
https://docs.djangoproject.com/en/3.1/topics/http/urls/

What is the url.py file that opens home using wagtail?

I'm starting using Wagtail + Django.
Generally, in Django you set the urls path in a urls.py file.
However, I cannot find the url.py that says to my app, when users visits main domain (local http://127.0.0.1:8000/) show home_page.html view.
I'm following the get_started tutorial.
And used this command to generate the basic apps:
wagtail start elim
This generated: a) elim, b) home, c) search apps.
Only elim app contains a urls.py, but it doesn't set a path for home:
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from wagtail.admin import urls as wagtailadmin_urls
from wagtail.core import urls as wagtail_urls
from wagtail.documents import urls as wagtaildocs_urls
from search import views as search_views
urlpatterns = [
url(r'^django-admin/', admin.site.urls),
url(r'^admin/', include(wagtailadmin_urls)),
url(r'^documents/', include(wagtaildocs_urls)),
url(r'^search/$', search_views.search, name='search'),
]
This is my project structure:
So how does going to "/" open the home page???
The home dir is served by wagtail internal mechanism. Scroll to the end of the file elim/urls.py to find this :
urlpatterns = urlpatterns + [
# For anything not caught by a more specific rule above, hand over to
# Wagtail's page serving mechanism. This should be the last pattern in
# the list:
url(r"", include(wagtail_urls)),
# Alternatively, if you want Wagtail pages to be served from a subpath
# of your site, rather than the site root:
# url(r"^pages/", include(wagtail_urls)),
]
So, continue to read the tutorial, I'm sure you will soon or later discover the Page models and everything provided by wagtail.
Try adding a view function in your app's views.py file that renders home_page.html when the user goes to "/".
in views.py write this:
def home_page(response):
return render(response, "home/home_page.html")
then map this to ur urs.py file
url_patterns = [
path("", views.home_page)
]
then add this url to your url conf

GET http://localhost:8000/add/ Page not found

I've been working on this application using my localhost:8000 for a while now and everything had been working smoothly. However now that I have tried to add a new url: /add/. For some reason it doesn't recognise the URL. I believe maybe there's something wrong with how I've wrote my code but I haven't quite found it. Any help would be great!
To provide context I started of in my urls.py file where I created a new path: path('add', views.ProjectCreateView.as_view(), name='add'),
I then moved over to my views.py file and imported the CreateView as so:
from django.views.generic import CreateView.
From there I then created a class for the view:
class ProjectCreateView(CreateView):
model = Project
template_name = 'budget/add-project.html'
fields = ('name', 'budget')
Following this I then created another file within my budget folder nested in my templates folder. The file name add-project.html. I don't think there's anything wrong with this file but just to guarantee this is how I linked my html file:
{% extends 'budget/base.html' %}
{% load static %}
{% block content %}
This is the exact message I get when I run http://localhost:8000/add/
"No Project matches the given query."
ULRS.PY in main working folder:
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.project_list, name='list'),
path('add', views.ProjectCreateView.as_view(), name='add'),
path('<slug:project_slug>/', views.project_detail, name='detail')
]
URLS.PY in subfolder:
from django.urls import path, include
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('budget.urls'))
]
When you request /add/ with the trailing slash, this does not match the add path but does match the <slug:project_slug>/ path, so it tries your project_detail view with project_slug set to "add".

Django Url Redirection

I have a problem with my project & I hope that you will help me figure it out.The main problem is that my project is a one-single page template, so I don't have so many views , but I want to know , how to redirect to my homepage
from django.conf.urls import url
from django.contrib import admin
from iubestete import views as iubestete_views
urlpatterns = [
url(r'^$', iubestete_views.index),
url(r'^',iubestete_views.index,name="portal"),
url(r'^admin/', admin.site.urls),
]
here is my urls.py file , which function should I import or what should I do? I mean, I want to know for example, if a person types "http://127.0.0.1:8000/adsnjiwadi/" ,how can I redirect that link to my homepage(index.html)?Thank you so much & I hope that you'll have a great day:) Peace:)
Your code url(r'^',iubestete_views.index,name="portal") in urls.py already catch all URL pattern, it will direct to your home page.
eg: http://127.0.0.1:8000/adsnjiwadi, http://127.0.0.1:8000/sfddasfdfaf/ddfsaf, etc. will go to your home page (index).
In your urls.py
url(r'^(?P<garbage>.*)/$', views.garbage,name='redirect')
In your views.py
from django.core.urlresolvers import reverse
def garbage(request, garbage):
return HttpResponseRedirect(reverse('index'))
This is is a hacky method. Anything other than your root url will return to index url.

Can't display new html page with href from homepage

The only examples I find. are related to issues with login page and iteration to other pages but not in the way I have the problem, so here is the issue I have to deal with -
I want to display a form for creating an account with multiple steps, using modals, when a user access the button "subscribe"
on my homepage.html I have this:
<a onClick="window.location.href='account'" target="_blank">
<input type="submit" value="account">
</a> `
...which is supposed to go to a new account.html page, in the same folder as my homepage.html
in my app's urls.py, where the apps' name is homepage I have:
from django.conf.urls import patterns, url
from homepage import views
urlpatterns = patterns('',
url(r'^$', views.homepage, name='homepage'),
url(r'^account$', views.account, name='account'),
)
and in my views I have:
from django.shortcuts import render
from homepage.models import Email
def tmp(request):
latest_email_list = Email.objects.order_by('-pub_date')[:0]
context = {'latest_email_list': latest_email_list}
return render(request, 'home_page/homepage.html', context)
def homepage(request):
return render(request, 'home_page/homepage.html')
def account(request):
return render(request, 'home_page/account.html')`
when I click on the button I get
Not Found
The requested URL /account was not found on this server.
I am a complete beginner in django and python so I really haven't yet wrapped my mind on how to work properly with the urls, views, and models together but I assume I have something wrongly defined in my views
would be grate if someone could help me setting this up,
Thanks
I only want to thank all those who took time to check my question and tried to give a solution.
I think it was my mistake that I did not post the code I have in my main urls.py file, so here it is:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', include('home_page.urls', namespace="homepage")),
url(r'^admin/', include(admin.site.urls)),
)
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
Apparently, the problem was in that first prefix of the first url in the list:
I changed
url(r'^$'
for
url(r''
and now it calls whatever links I provide in my html pages.
Thanks all again

Categories