(Django) Why would my code not execute in an .html template? - python

this is my first post. I'll try get things right first time. I am having a play around with django and slowly creating a dummy store website. I'm following along a Corey Schafer YouTube tutorial and I didn't have this issue on my first run, so scratching my head now!
My problem is that my .html template is not displaying the listing item when I run the page. I still see the <h1>DaftPrices Store Homepage</h1>, but not the listings.
This is my template (store_home.html):
<!DOCTYPE html>
<html lang="en">
<head>
<title>DaftPrices - Home</title>
</head>
<body>
<h1>DaftPrices Store Homepage</h1>
{% for listing in listings %}
<p>{{ listing.item }}</p>
{% endfor %}
</body>
</html>
This is saved in a store dir, inside a templates dir, inside the store app.
Image of directories
This is my app views.py:
from django.shortcuts import render
listings = [
{
'seller': 'ABCDEFG',
'title': 'Something to sell',
'date_posted': '28th August 3030'
}
]
def store_home(request):
context = {'listing': listings}
return render(request, 'store/store_home.html', context)
def store_about(request):
return render(request, 'store/store_about.html')
To clarify, the page pulls the template, but the "code" isn't working
I have tried re-writing the dummy listings and changing the variables. I wasn't expecting this to do anything (and it didn't), but that was my first shot.
I checked my project's settings.py folder to double check that I had added the store app into "installed apps". I believe this is correct, and was identical to what I did on my previous run without the issue:
store app ; apps.py:
from django.apps import AppConfig
class StoreConfig(AppConfig):
name = 'store'
project ; settings.py:
INSTALLED_APPS = [
'store.apps.StoreConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
I've had a look at other stackoverflow listings which seem like they are relevant to my problem, but I'm struggling to identify the key info other than making sure the context is called for correctly. I can't see any issues with mine, hence I'm here.

You have missed the s in listings context key:
def store_home(request):
context = {'listing': listings}
return render(request, 'store/store_home.html', context)
def store_home(request):
context = {'listings': listings}
return render(request, 'store/store_home.html', context)
Corey did awesome job. I have completed his course and I work with Django today.

Related

KeyError: 'Unable to find stateless DjangoApp called app'

Why the DjangoApp app can't be found?
Given result
After executing manage.py runserver in the console Django is starting properly but in case I'm calling http://127.0.0.1:8000/dash_simple/app1/ a KeyError was thrown:
Django Version: 3.1.3
Exception Type: KeyError
Exception Value:
'Unable to find stateless DjangoApp called app'
Expected result
After executing manage.py runserver in the console Django is starting properly and the related page is shown for http://127.0.0.1:8000/dash_simple/app1/
dash_test/urls.py
urlpatterns = [
path('dash_simple/', include ('dash_simple.urls')),
]
dash_test/settings.py
INSTALLED_APPS = [
'dash_simple.apps.DashSimpleConfig',
]
dash_test/dash_simple/apps.py
class DashSimpleConfig(AppConfig):
name = 'dash_simple'
dash_simple/urls.py
urlpatterns = [
path('', views.home, name='home'),
path('app1/', views.app, name='app')
]
dash_simple/views.py
def home(request):
return render(request, template_name='dash_simple/home.html')
def app(request):
return render(request, template_name='dash_simple/app1.html')
dash_simple/templates/dash_simple/app1.html
{% load plotly_dash %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>App 1</title>
</head>
<body>
<H1>I'm App 1</H1>
<p>
{% plotly_app name="app" %}
</p>
</body>
</html>
Faced similar issue. In dash_simple/urls.py you need to import your dash application i.e.:
from dash_simple import your_dash_script_file_name
As simple as that!
For future reference. In my case getting 'Unable to find stateless DjangoApp called "AppName"'. For one of my plotly app it worked and for the other one i did not. I started verifying what one off them had and the other not.
After some hours i noticed this set of imports i made few days ago on the /views of the app that was serving the html template that showed the plot, while setting the first.
from plotly.offline import plot
import plotly.graph_objs as go
from .plot import *
I copied this to the other app that rendered had the view of the second plot. but the compilation failed because the 3rd import was not being found. Because of this i went into the reference of the import in the first plot and it was the module that had all the code of the first plot, so i changed the last import on the views of the django app that rendered my second plot
Basically. My solution was to also do the three imports on the views of the django app that is rendering the html that contains the plot and change the last line to import the script/module of the dash plotly app that i'm looking to render.

Login page doesn't show in django all-auth

I am having a problem with django allauth login page. I was able to complete the tutorial django all-auth, however I encountered a problem with the login page when I tried http://localhost/accounts/login/ nothing is showing but only a blank page.
And the tutorial does not show how to create the login page, so I guess that is the last step I should be working on.
What I did until now is this,
settings.py
INSTALLED_APPS = (
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
)
SOCIALACCOUNT_PROVIDERS = {'google': {'SCOPE': ['email'],
'AUTH_PARAMS': {'access_type': 'online'}
}
}
# Django all auth settings
AUTHENTICATION_BACKENDS = (
# Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend',
)
SITE_ID = 1
urls.py
url(r'^accounts/', include('allauth.urls')),
Also I already added a social application in the Django admin and it's required fields.
Thank you soo much, your help is much appreciated.
Piggybacking off of #bharat's post and for others stumbling across this post trying to figure out why nothing is being displayed...
django-allauth comes with templates that have all of the content that you already need and even a few templates that you may have not added yourself. But, as comes with the templates, comes the project-owners project structure.
If you want all of your django-allauth pages to use the content that it comes with, you will need to copy and paste the templates into your template folder and then update them to work with your project structure...
So, you will need to do to the typical installation process and then add all of the templates as well. I just can't find this documented anywhere. You can see all of the templates here.
EDIT: If you look closely at the top of the templates page it says 'Overridable templates' which clearly answers the issue that I had for hours. But, if you missed that as I did. There's your issue.
If you're not planning on using the django-allauth views though, you don't have to. You can totally implement social-authentication without using all of the views. So, it's up to you... But, once you implement them you will realize that it does save you an incredible amount of time in setting your future projects up. It's just a matter of getting it working the first time.
There are likely a couple of things you will have to change in the templates for everything to work.
Update the <title> block that is {% block head_title %}.
Update the {% block content %} to whatever you call your body block.
Import django-crispy-forms with {% load crispy_forms_tags %}.
Make all of your forms crispy.
If you're using all of the django-allauth views. Chances are you want an account view so you will need to create that as well because that does not come in the views.
But, you can totally just use the same pattern that django-allauth does and create something like accounts/<username>/
Having a look at this GitHub Repo would help you to create a login page:
https://github.com/pennersr/django-allauth/blob/master/allauth/templates/account/login.html.
You should also ensure that the login page has appropriate url-mappings on urls.py file.
Hope, that helps.

how to handle the render respose in django

first page of my application : home.html
i have written the view to render the request to "localhost:8080/contact"
def contact(request):
..
return render(request,'template/contact.html',{'contact': [ htmlString ] })
Now, localhost:8080/contact is working correctly and showing the output. but i need to include the same output in home.html
i tried to add <a href ="template/contact.html></a> in home.html but it is now showing the results.
Can someone explain how to do this..
I am beginner in python django development.

Incorporating existing html pages into Django

I have several hundred static html pages, with an index html page, that I need to bring into Django. I can't figure out the easiest way to do that, I know I'm missing something simple. Any advice?
Nothing fancy needed, just need to dump them in a directory and allow users to navigate to them.
You need to create a view and a url for each html template, iI'm going to put you a simple example here but it's highly recommended that you read Django's documentation or a tutorial :
First, you create a view in a views.py file :
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views.generic import View
class LoadTemplateView(View):
template_name = ['thenameofyourdjangoapp/yourtemplatename.html']
#You put any code you may need here
def get(self, request, *args, **kwargs):
return render(request, self.template_name)
Then, you must create a url that reads that view in a urls.py file :
from django.conf.urls import patterns, url
#Here you import from views the view you created
from .views import LoadTemplateView
urlpatterns = patterns(
url(r'^myurl/$', LoadTemplateView.as_view(), name="load_template"),
)
Last, in your let's say home html template, you assign this url to a submit button in order to call it by the name you gave it on urls.py (load_template in this case) :
<html>
<body>
<div>
<a class="option-admin" id="id_go" href ="{% url 'yourdjangoappname:load_template' %}"> Go to template </a>
</body>
</html>
</div>
As I said anyway, it's better that you read the complete Django documentation as well:
https://docs.djangoproject.com/en/1.9/
If these are legacy static pages that you do not plan to touch again, then I'd leave django out of it. I'd put them all in a directory or subdomain and serve them directly from the server (probably nginx, maybe apache, whatever you're using). As a general rule, you don't want Django serving static assets, you want the proxy server serving them.
You COULD move them into Django and manage them like other Django static assets, as described in the Managing Static Files Documentation, but if they're already out there, then there's not a whole lot of advantage over just serving them as outlined above.
And finally, if you wish to fully integrate them into your Django site, then you should probably start with the template documentation.

Django image not getting uploaded

We are making our school site on Django, we made a gallery app but i think the images are not getting uploaded to designated folder, rather they are not even getting uploaded i think so .
Code : -
# views.py
def upload(request, template_name="gallery/form.html"):
form = GalleryForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
messages.success(request, "image has been uploaded")
return redirect('gallery.views.index')
return render(request, template_name,{'form':form})
from django.db import models
# models.py
class GalleryPhoto(models.Model):
image = models.ImageField(upload_to='pic_folder/')
description = models.CharField(max_length=50)
def __unicode__(self):
return self.image.url
The rest of the code can be seen in this repo
Note : the the gallery template contains some conflicts but that is not the actual problem.
It took me a while to notice it, because it's kinda tricky. But in retrospect it's obvious.
So after configuring MEDIA_URL = "/MEDIA/" I noticed that http://127.0.0.1:8000/media/ was giving me a 404. If everything is configured correctly (and it is) then usually the problem is conflicting urls. See the url patterns used in django are always evaluated in order. That means if you have urls like so:
url(r'^mypage/', 'myapp.mypage'),
url(r'^mypage/another/', 'myapp.different')
Then the second url will never be available. Why? because there's nothing up there that tells the url dispatcher that the first url should end at mypage/. As far as it's concerned, everything starting with http://DOMAIN/mypage/ will be caught and passed to the first function.
To avoid that, we use the $ sign to tell the dispatcher at what point to stop. Like so:
url(r'^mypage/$', 'myapp.mypage'),
url(r'^mypage/another/$', 'myapp.different')
Now let's look at your last two urls:
url(r'^', include('pages.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
See that? url(r'^' swallows everything that comes after it, so no media is being served. It's true that pages.urls uses a dollar for its first url:
url(r'^$', views.index, name='index'),
but that doesn't matter for the main url dispatcher, which evaluates r'^' first. What's the solution? the simplest would be to move the pages urls to the end:
url(r'^ckeditor/', include('ckeditor.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += patterns('', url(r'^', include('pages.urls')))
You can also isolate that one problematic url from the others using a direct call, like so:
url(r'^/$', 'pages.views.index'),
url(r'^pages/$', include('pages.urls')),
After that, this will work:
<img src="{{ MEDIA_URL }}{{ image.image.url }}" alt="{{ image.description }}">
p.s.
Eventually you're going to pass the media and static files through your server, when you move to deployment level, so maybe the whole thing wouldn't matter then. If you do decide to keep the r'^' in use, just keep in mind that it might cause conflicting problems with other urls, so be sure to always put it last.

Categories

Resources