Django- 2nd App within project, page not found - python

I can not figure out what I am doing wrong within the second app my project called 'weather'. The first part, 'home', works fine. I made it so that an empty url '' and a url with '/home/' both map to the home page. Even the link I created in my navigation bar to the home page works, but the same is not true for the weather link. I end up getting 'Page not found 404' Error.
Here is an overview:
Project structure
I included the app 'weather' in the settings installed apps.
Here urls.py file in the main project folder:
from django.contrib import admin
from django.urls import path, include
from weather import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
path('', include('weather.urls')),
]
The urls.py file for my weather app:
from weather import views
from django.urls import path
urlpatterns = [
path('', views.GetWeather.as_view(), name='weather'),
]
The views.py for the weather app:
from django.views import generic
import requests
from django.shortcuts import render
from .models import City
from .forms import CityForm
class GetWeather(generic.ListView):
queryset = City.objects.order_by('-requested')
template_name = 'weather.html'
def index(request):
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=c5a079de62bccff63d64ac8989f87e37'
form = CityForm()
cities = City.objects.all()
weather_data = []
for city in cities:
r = requests.get(url.format(city)).json()
city_weather = {
'city' : city.name,
'temperature' : r['main']['temp'],
'description' : r['weather'][0]['description'],
'icon' : r['weather'][0]['icon'],
}
weather_data.append(city_weather)
context = {'weather_data' : weather_data, 'form' : form}
return render(request, 'templates/weather.html', context)
The models.py for the weather app:
from django.db import models
from django.contrib.auth.models import User
class City(models.Model):
name = models.CharField(max_length=30)
requested = models.DateTimeField(auto_now_add = True)
class Meta:
ordering = ['-requested']
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'cities'
The weather.html template:
<!DOCTYPE html>
{% extends "base.html" %}
{% block content %}
<html>
<style>
body {
font-family: "Roboto", sans-serif;
font-size: 18px;
background-color: rgba(0, 0, 0, .75);
}
.head_text{
color: white;
}
.card{
box-shadow: 0 16px 48px #E3E7EB;
}
</style>
<div class="container">
<div class="row">
<div class="col-md-8 mt-3 left">
{% for city_weather in weather_data %}
<div class="card mb-4">
<div class="card-body">
<h2 class="media-left">
<figure class="image is-50x50">
<img src="http://openweathermap.org/img/w/{{ city_weather.icon }}.png" alt="Image">
</figure>
</h2>
<div class="media-content">
<div class="content">
<p>
<span class="title">{{ city_weather.city }}</span>
<br>
<span class="subtitle">{{ city_weather.temperature }}° F</span>
<br> {{ city_weather.description }}
</p>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</html>
{% endblock content %}
This is the blog.urls:
from . import views
from django.urls import path
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
]
I greatly appreciate anyone who took the time to read through this and help me.

You will have to change either blogs/urls.py or weather/urls.py first URL match. It depends on what you want to see on your base URL.
# weather/urls.py
from weather import views
from django.urls import path
urlpatterns = [
path('weather/', views.GetWeather.as_view(), name='weather'),
]
# blog/urls.py
from . import views
from django.urls import path
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('blog/<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
]
This shall resolve, assuming you want weather details on first page.

Related

no such table: (Django)

when i run my code (its for a project) i get this error: "no such table: encyclopedia_article". The error appears to come from 9 line of views.py (obj = article.objects.get(id=1). here is the code:
views.py
from django.shortcuts import render
from django.http import HttpResponse
from . import util
import random
from .models import article
from .forms import ArticleForm
def index(request):
obj = article.objects.get(id=1) #THIS IS WHAT APPERS TO CAUSE THE ERROR
context = {
'object': obj
}
entries = util.list_entries()
random_page = random.choice(entries)
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries(),
"random_page": random_page,
})
def CSS(request):
return render(request, "encyclopedia/css_tem.html", {
"article_css": "css is slug and cat"
})
def Python(request):
return render(request, "encyclopedia/python_tem.html", {
"article_python": "python says repost if scav"
})
def HTML(request):
return render(request, "encyclopedia/HTML_tem.html", {
"article_HTML": "game theory: scavs are future humans"
})
def Git(request):
return render(request, "encyclopedia/Git_tem.html", {
"article_Git": "github is git"
})
def Django(request):
return render(request, "encyclopedia/Django_tem.html", {
"article_Django": "this is a framework"
})
def new_article(request):
form = ArticleForm(request.POST or None)
if form.is_valid():
form.save()
context = {
'form': form
}
return render(request, "encyclopedia/new_article_tem.html", context)
models.py:
class article(models.Model):
title = models.CharField(max_length = 120)
description = models.TextField(blank=True, null = False)
forms.py:
from django import forms
from .models import article
class ArticleForm(forms.ModelForm):
class Meta:
model = article
fields = [
'title',
'description'
]
urls:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("", views.CSS, name="CSS"),
path("", views.Python, name="Python"),
path("", views.HTML, name="HTML"),
path("", views.Git, name="Git"),
path("", views.Django, name="Django"),
path("", views.new_article, name="new_article")
]
second urls (in other directory (there is encyclopedia and wiki this one is in wiki the last one in encyclopedia)):
"""wiki URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path
from encyclopedia import views
from encyclopedia.views import index
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("encyclopedia.urls")),
path('CSS/', views.CSS, name="CSS"),
path('Python/', views.Python, name="Python"),
path('HTML/', views.HTML, name="HTML"),
path('Git/', views.Git, name="Git"),
path('Django/', views.Django, name="Django"),
path('new_article/', views.new_article, name="new_article"),
path('main/', index)
]
new_article_tem.html:
{% extends "encyclopedia/layout.html" %}
{% block title %}
New Article
{% endblock %}
{% block body %}
<h1>Create Article</h1>
<form method = 'POST' action = "{% url 'index' %}"> {% csrf_token %}
<input type = 'submit' value='Save'>
</form>
{% endblock %}
IM NOT SURE IF THIS ONES ARE USEFULL BUT STILL IM PUTTING ALMOST EVERYTHING:
index.html:
{% extends "encyclopedia/layout.html" %}
{% block title %}
Encyclopedia
{% endblock %}
{% block body %}
<h1 id="demo" onclick="add_article()">Add article</h1>
<ul>
{% for entry in entries %}
<li><a href = /{{entry}}>{{ entry }}</a></li>
{% endfor %}
{% for article_title in created_articles %}
<li>{{article_title}}</li>
{% endfor %}
<li>{{title}}</li>
</ul>
{% endblock %}
layout.html:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet">
</head>
<body>
<div class="row">
<div class="sidebar col-lg-2 col-md-3">
<h2>Wiki</h2>
<form>
<input class="search" type="text" name="q" placeholder="Search Encyclopedia">
</form>
<div>
Home
</div>
<div>
<a href = "/new_article" >Create New Article</a>
</div>
<div>
Random Page
</div>
{% block nav %}
{% endblock %}
</div>
<div class="main col-lg-10 col-md-9">
{% block body %}
{% endblock %}
</div>
</div>
</body>
</html>
Try to use this :-
python manage.py makemigrations
and then
python manage.py migrate

django 404 page not found error http://localhost:8000/static/feed.html

django is adding the /static/ url to my path and i don't know why
Page not found (404) Request Method: GET Request URL: http://localhost:8000/static/feed.html 'feed.html' could not be
found
Page not found (404) Request Method: GET Request URL: http://localhost:8000/static/messages.html 'messages.html' could
not be found
Page not found (404) Request Method: GET Request
URL: http://localhost:8000/static/upload.html 'upload.html' could not
be found
here is my views.py
from django.shortcuts import render
from django.views.generic import TemplateView, ListView, CreateView
from app.models import SendSMS
from app.forms import SendSMSForm
from django.urls import reverse_lazy
from app.utils import send_twilio_message
from django.conf import settings
import datetime
# Create your views here.
# Create your models here.
def index(request):
return render(request, 'index.html')
def feed(request):
return render(request, 'feed.html')
def upload(request):
return render(request, 'upload.html')
def messages(request):
return render(request, 'messages.html')
def statistics(request):
return render(request, 'statistics.html')
class SendSmsCreateView(CreateView):
model = SendSMS
form_class = SendSMSForm
template_name = 'messages.html'
success_url = reverse_lazy('send_sms')
def form_valid(self, form):
number = form.cleaned_data['to_number']
body = form.cleaned_data['body']
# call twilio
sent = send_twilio_message(number, body)
# save form
send_sms = form.save(commit=False)
send_sms.from_number = settings.TWILIO_PHONE_NUMBER
send_sms.sms_sid = sent.sid
send_sms.account_sid = sent.account_sid
send_sms.status = sent.status
send_sms.sent_at = datetime.datetime.now()
if sent.price:
send_sms.price_unit = sent.price_unit
send_sms.save()
return super(SendSmsCreateView, self).form_valid(form)
here is my app urls.py
from . import views
from django.contrib import admin
from django.conf.urls import url
from django.urls import path, include
app_name = 'app'
urlpatterns = [
path('', views.index, name='index'),
path('', views.feed, name='feed'),
path('', views.upload, name='upload'),
path('', views.messages, name='messages'),
path('', views.statistics, name='statistics'),
]
here is my project urls.py
from django.contrib import admin
from django.conf.urls import url
from django.urls import path, include
from app.views import SendSmsCreateView
url(r'^admin/', admin.site.urls),
# ... your url patterns
path('', include('app.urls', namespace='app')),
url(
regex=r'^app/$',
view=SendSmsCreateView.as_view(),
name='send_sms'
),
]
here is my index.html file
{% load static %}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<li class="nav-item">
<a href=" {% static 'feed.html' %} " class="nav-link">
<i class="nav-icon fas fa-th"></i>
<p>
Feed
<span class="right badge badge-danger">New</span>
</p>
</a>
</li>
<li class="nav-item has-treeview">
<a href=" {% static 'messages.html' %} " class="nav-link">
<i class="nav-icon fas fa-copy"></i>
<p>
Compose Message
</p>
</a>
</li>
<li class="nav-item has-treeview">
<a href=" {% static 'upoad.html' %} " class="nav-link">
<i class="nav-icon fas fa-chart-pie"></i>
<p>
Upload CSV
</p>
</a>
</li>
</body>
some of the noticed faults are
context is missing in view, add an empty brackets as shown, which will server as context now, later on you can add key and values reqired
def index(request):
return render(request, 'index.html', {})
fault in indexing url, need to add non over lapping regex patters
path('', views.index, name='index'),
path('feed/', views.feed, name='feed'),
path('upload/', views.upload, name='upload'),
path('messages/', views.messages, name='messages'),
path('statistics/', views.statistics, name='statistics'),
change the url to path as it outdated
path('app/',
view=SendSmsCreateView.as_view(),
name='send_sms'
),
What i did was to add the namespace in the html file
before i used
<a href=" {% url 'feed.html' %} " class="nav-link active">
the above didn't work so i changed it to
<a href=" {% url 'app:feed' %} " class="nav-link active">

Django Teamplate Error name 'Post_title' is not defined

I'm trying to render index HTML and get post title from database but I'm getting error. I define in views post database but still getting error
name 'Post_title' is not defined
my app/views.py
from django.shortcuts import render, get_object_or_404
from django.shortcuts import reverse
from .models import BlogPost,comments
def index(request):
Post_list = BlogPost.objects.all()
template_name = 'front/index.html'
return render(request, template_name,{Post_title:"Post_title",})
def post_detail(request):
return render(request, 'front/post_detail.html')
my app/urls.py
from django.urls import path
from .import views
urlpatterns = [
path('', views.index, name = 'index'),
path('<int:BlogPost_id>/', views.post_detail, name='Post Detail')
]
my project/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
from froala_editor import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
path('froala_editor/', include('froala_editor.urls'))
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
my index.html template
<div class="col-md-8 mt-3 left">
{% for post in Post_list %}
<div class="card mb-4">
<div class="card-body">
<h2 class="card-title">{{ post.Post_title }}</h2>
</div>
</div>
{% endfor %}
</div>
You are not sending the Post_list to the template through context. Send it like this
return render(request, template_name, {'Post_list':Post_list})

How can I make a view for a section of Index.html separately?

So, I have a website where the user clicks "my blog" on the navbar, which scrolls down to that section of the index.html (ex. 8000/#blog-section). I already have the Contact form working on the index page.
Now I am trying to create the blog logic to render out three blog posts, but it is showing up blank?
Can I create a separate view for the same "index.html" page?
Views.py
def index_view(request):
posts = Post.objects.all().order_by('-created_on')
context ={
'posts': posts,
'name': name,
}
form = ContactForm()
if request.method == 'POST':
form = ContactForm(data=request.POST)
if form.is_valid():
# Send email goes here
name = request.POST.get('name')
subject = request.POST.get('subject')
email = request.POST.get('email')
message = request.POST.get('message')
template = get_template('contact_form.txt')
context = {
'subject': subject,
'email' : email,
'message' : message
}
content = template.render(context)
email = EmailMessage(
"Message from Portfolio",
content,
"New inquiry | Portfolio" + '',
['myemail#gmail.com'],
headers = {'Reply to': email}
)
email.send()
return HttpResponseRedirect("/")
return render(request, 'index.html', {'form': form}, context)
Urls.py /blog
from django.urls import path
from . import views
urlpatterns = [
path("", views.blog_index, name="blog_index"),
path("<int:pk>/", views.blog_detail, name="blog_detail"),
path("<category>/", views.blog_category, name="blog_category"),
]
Urls.py /portfolio
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from .views import index_view, post_view
urlpatterns = [
path('admin/', admin.site.urls),
path('tinymce/', include('tinymce.urls')),
path('', index_view),
path('post/', post_view),
path("#blog-section/", include("blog.urls")),
]
Template
<div class="row d-flex">
{% for post in posts %}
<div class="col-md-4 d-flex ftco-animate">
<div class="blog-entry justify-content-end">
<a href="single.html" class="block-20"
style="background-image: url('{{ post.post_img.url }}');">
</a>
<div class="text mt-3 float-right d-block">
<div class="d-flex align-items-center mb-3 meta">
<p class="mb-0">
<span class="mr-2">{{ post.created_on.date }}|
Categories: </span>
Admin
<span class="icon-chat"></span> 3
</p>
</div>
<h3 class="heading">{{post.title}}</h3>
<p>{{post.overview}}</p>
</div>
</div>
</div>
{% endfor %}
</div>
For some reason you have put your posts in a separate dictionary from the form. That's not how it works. Put all the context in a single dict.
context = {
'posts': posts,
'name': name,
'form': form
}
return render(request, 'index.html', context)
And to answer your question: no you can't (at least not without building up your page with Ajax). One URL equates to one view.

Django dynamic url

I trying to open content inside poster using a dynamic url, but I am facing a problem
my code is for a simple web page containing some movie posters and when I click on a poster new template on a new page should open which will show information about this poster.
but whenever I click on a poster same template(index.html) opens in a new page instead of page.html
eg
127.0.0.1:8000/home is web page with all posters and I clicked on poster1 with id=1 then in new page 127.0.0.1/home/1 will open but it is still index.html with all posters, not page.html in which content of poster1 id=1 is stored.
Here is my code
homepage/models.py
from django.db import models
class Poster(models.Model):
poster_name = models.CharField(max_length=20)
poster_img = models.FileField(upload_to="poster_image/")
def __str__(self):
return self.poster_name
class Poster_page(models.Model):
poster = models.ForeignKey(Poster, default= 1)
poster_name = models.CharField(max_length=20)
poster_img = models.FileField()
poster_details = models.TextField()
homepage/views.py
from django.shortcuts import render_to_response
from .models import Poster, Poster_page
def poster(request):
pos = Poster.objects.all()
return render_to_response('index.html', {'pos':pos})
def poster_page(request, id=1):
poster_pg = Poster_page.objects.all()
return render_to_response('page.html', {'poster_pg':poster_pg})
homepage.url
from django.conf.urls import url
from.views import poster, poster_page
urlpatterns = [
url(r'^',poster),
url(r'^home/(?P<id>/d+)/$', poster_page),
]
poster.url
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^home/',include('homepage.urls', namespace='home'))
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
index.html
<body>
<div class="row">
{% for poster in pos %}
<div class="col-md-4">
<img src="{{ poster.poster_img.url }}" alt="image"><h3>{{ poster.poster_name }}</h3>
</div>
{% endfor %}
</div>
page.html
<body>
<div class="row">
<img src="{{ poster_img.url }}" alt="image"><h2>{{ poster_name }}</h2>
</div>
<div class="row">
<h2>{{ poster_details }}</h2>
</div>
homepage.url
Replace d/+ by \d+
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.poster),
url(r'^(?P<id>\d+)/$', views.poster_page),
]
Then Try:
from django.shortcuts import render,get_object_or_404
def poster_page(request, id):
poster_pg = get_object_or_404(Poster_page, id=id)
return render_to_response('page.html', {'poster_pg':poster_pg})
and yes you also need <a href="/home/{{poster.id}}/">.
In index.html you have not defined correct url in href to open poster detail.
Correct syntax would be like this:
<img src="{{ poster.poster_img.url }}" alt="image"><h3>{{ poster.poster_name }}</h3>
I think the issue is in the view with the context variable -
return render_to_response('index.html', {'pos':pos})
should be -
return render_to_response('index.html', {'poster':pos})
Because in you are calling {{poster.id}} in index template.

Categories