Django dynamic url - python

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.

Related

How do I fix this Getting no reverse match error in django

I have been facing this issue. And I have a url name post-page-detail but then also getting error please
See the error screenshot below.
My singlepost.html html page
<a href="{% url "post-detail-page" slug=post.slug %}">
<h2>{{post.tractor_company}} || {{post.tractor_model}}</h2>
<pre><h5>{{post.implimentaion}}</h5>
{{post.farmer}}
Uplode Date : {{post.date}}</pre>
</a>
</div>
URLs.py
from . import views
urlpatterns = [
path("",views.starting_page,name = "starting-page"),
path("posts",views.posts,name = "post-page"),
path("posts/<slug:slug>",views.post_detail,name="post-detail-page"),
]
View.py
from django import forms
from django.contrib.auth.models import User
from django.shortcuts import render, redirect ,get_object_or_404
from .models import Post, Farmer
# Create your views here.
from django.http import HttpResponseRedirect
# Create your views here.
def starting_page(request):
return render(request,"tractor/index.html")
def posts(request):
qs = Post.objects.all()
context = {"posts":qs}
return render(request,"tractor/all-post.html",context)
def add_post(request):
pass
def post_detail(request,slug):
indentified_post = get_object_or_404(Post,slug=slug)
return render(request,"blog/post-detail.html",{'post':indentified_post})
i am iterating through posts and using the post-detail.html page
all-post.html.
{% load static %}
{% block title %}
All Tractors
{% endblock %}
{% block content%}
<section id="all_events">
<br>
<h1 style="text-align:center;">All Tractors</h1>
<ul>
{% for post in posts %}
<br>
{% include "tractor/includes/singlePost.html" %}
{% endfor %}
</ul>
</section>
{% endblock %}
Root urls.py
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path("",include(("tractor.urls","tractor"))),
]
The 'tractor' part in the path('', include(('tractor.urls', 'tractor'))) in the include(…) function [Django-doc] specifies the app_namespace. This means that for all URLs you use in the tractor.urls urls, you should prefix this with tractor::
<a href="{% url 'tractor:post-detail-page' slug=post.slug %}">
…
</a>

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- 2nd App within project, page not found

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.

Show a list of Posts in a different URL

Django Blog APP comes with an out of the box index.html where it shows a list of all posts.
I need to show this list in a new URL, when I somply copy the html code from index.html and paste onto planoacao.html it doesn´t show anything.
This is the index.html:
{% for post in post_list %}
<div class="card mb-4" style="width: 18rem; ">
{% if post.get_finalizado_display == 'Não' %}
<!--<p class="card-text text-muted h6"> NOK </p>-->
<div class="card-body" style="background-color:#FF0909;">
{% else %}
<!--<p class="card-text text-muted h6"> ok </p>-->
<div class="card-body">
{% endif %}
{% endfor %}
This is my views.py:
from django.views import generic
from .models import Post
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'index.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'
class Calendar(generic.DetailView):
model = Post
template_name = 'calendar.html'
class Planoacao(generic.DetailView):
model = Post
template_name = 'planoacao.html'
This is my urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
url(r'^planoacao/', TemplateView.as_view(template_name="planoacao.html")),
url(r'calendar', TemplateView.as_view(template_name="calendar.html")),
url(r'^admin/', admin.site.urls),
url(r'^', include('blog.urls'), name="Blog"),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
How can I show a list of all posts in a different URL? xxx/planoacao.html ? Simply copying the html from index.html doesn´t work.
Note that I don´t want to change the regular index.html post list, I just want to add a second post list page.
It seems you want to show your PostList view at /planoacao, so in urls.py you can hook this path up to that view:
url(r'^planoacao/', PostList.as_view()),
Note that in Django there is no direct link between the path of a view and the template used. You can use any template with any path, all you have to do is define which template to use in the view.

Use different SQL data depending on url in Django

If i have a url that is "someurl/report/1/" where "report" is an app and "1" corresponds to a certain id of a model in my SQL database, how would i substitute the variables in the template with that specific models data?
In my case I am writing a website that displays a surf report for different beaches. I have set it up so each SQL model id corresponds to a different beach. So if I wanted to use the data of beach "3" in the template, how would i display those in the html template?
TRACEBACK
Using the URLconf defined in surfsite.urls, Django tried these URL patterns, in this order:
^admin/
^report/ ^$ [name='index']
^report/ (?P[0-9]+)$ [name='get_report']
The current URL, report/1/, didn't match any of these.
#URLS.PY
from django.conf.urls import url
from django.conf.urls.static import static
from . import views
urlpatterns = [
# /index/
url(r'^$', views.index, name='index'),
# /report/
url(r'(?P<beach_id>[0-9]+)$', views.get_report, name='get_report'),
]
#MY TEMPLATE
<!DOCTYPE html>
<html>
{% load staticfiles %}
<link rel="stylesheet" type="text/css"
href="{% static 'report/css/style.css' %}"/>
<link href="https://fonts.googleapis.com/css?family=Biryani:300,400,800"
rel="stylesheet"/>
<head>
<title>REALSURF</title>
</head>
<body>
<h1>
<form id="search">
<input id="search" type="text">
</form>
</h1>
<div class="container">
<div class="column">
<div class="text">Wind</div>
<div class="number">{{Break.wind}}</div>
</div>
<div class="column">
<div class="text">Wave Height</div>
<div class="number">{{Break.low}}-{{Break.high}}</div>
</div>
<div class="column">
<div class="text">Tide</div>
<div class="number">{{Break.tide}}</div>
</div>
</div>
<h2>
REALSURF
</h2>
<h3>
A simple site by David Owens
</h3>
</body>
</html>
#MY MODEL
from __future__ import unicode_literals
from django.db import models
class Beach(models.Model):
name = models.CharField(max_length=50)
high = models.SmallIntegerField()
low = models.SmallIntegerField()
wind = models.SmallIntegerField()
tide = models.DecimalField(max_digits=3, decimal_places=2)
def __str__(self):
return self.name
#MY VIEWS
from django.http import Http404
from django.shortcuts import render
from .models import Beach
def index(request):
allBeaches = Beach.objects.all()
context = {
'allBeaches': allBeaches,
}
return render(request, 'report/index.html', context)
def get_report(request, id):
try:
beach = Beach.objects.get(id=id)
except Beach.DoesNotExist:
raise Htpp404("404")
return render(request, 'report/index.html', {'beach': beach})
If i understand you right, you want to create view, that render beach separately
You can do something like this, your view:
def get_beach(request, id)
beach = Beach.objects.get(id=id)
return render(request, 'path/to/your/template', {'beach':beach})
urls:
url(r'^someurl/report/(?P<id>[0-9]+)$', views.get_beach(), name='get_beach'),
template url to this page:
beach
Edited
Its your view, as i understand, this is detail view, but select all objects(Break.objects.all())
def detail(request, break_id):
try:
allBreaks = Break.objects.all()
except Break.DoesNotExist:
raise Http404("404")
return render(request, 'report/index.html', {'allBreaks': allBreaks})
so you have to change this on this:
def detail(request, break_id):
try:
break_detail = Break.objects.get(id=break_id)
return render(request, 'path/to/your/template', {'break_detail':break_detail})
except Break.DoesNotExist:
raise Http404("404")
then your url should look like this:
url(r'^someurl/report/(?P<break_id>[0-9]+)$', views.detail(), name='detail'),
or you can use get_object_or_404:
def detail(request, break_id):
break_detail = get_object_or_404(Break, id=break_id)
return render(request, 'path/to/your/template', {'break_detail':break_detail})
Url is the same.
So if you want to access to wind field, you just write this tempalte tag {{break_detail.wind}}
UPD2
change place from this
^admin/
^report/ ^$ [name='index']
^report/ (?P<beach_id>[0-9]+)$ [name='get_report']
to this:
^admin/
^report/(?P<beach_id>[0-9]+)$ [name='get_report']
^report/^$ [name='index']
and delete spaces in urls after report/

Categories