Use different SQL data depending on url in Django - python

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/

Related

Django. Url cant find view

I need help with {% url (url to template) %} when i try to open another view i see a NoRewerseMatch error.
here is my html file:
{% load static %}
<head>
<link href='{% static "navbar_style.css" %}' rel="stylesheet", type="text/css">
</head>
<header>
<nav class="headlist">
--->
<ul>
<li>O nas</li>
<li>Kontakt</li>
<li><a>Zajęcia</a></li>
</ul>
</nav>
</header>
my app(pages)/urls.py
from django.contrib import admin
from django.urls import path
from . import views
app_name = 'pages'
urlpatterns = [
path('', views.home_view, name='home_view'),
path('index/', views.index_view, name='index_view'),
]
views.py
import...
# Create your views here.
def home_view(request):
listoftexts = Text.objects.order_by('-pub_date')
context = {
'listoftexts': listoftexts
}
return render(request, 'pages/home.html', context)
def index_view(request):
listoftexts = Text.objects.order_by('-pub_date')
context = {
'listoftexts': listoftexts
}
return render(request, 'pages/index.html', context)
You can do it like this.
The name of the view is home_view:
path('', views.home_view, name='home_view'),
so you can use the {% url … %} template tag [Django-doc] with:
<a href="{% url 'home_view' %}">
If you use an app_name in the urls.py, you also need to prefix this in the url:
<a href="{% url 'pages:home_view' %}">
The url_name should be home_view not home. The name parameter in the path function is what you use to refernce the view.

I am trying to test a relationship with Inspection and Defect using Django and got an error in tests.py

I am trying to do a fun project that relates Inspections and Defects.
The error I got was Inspection() got an unexpected keyword argument partNum. Here is my urls.py.
from django.urls import reverse
from django.urls import resolve
from django.test import TestCase
from .views import home,inspection_defects
from .models import Inspection
# Create your tests here.
class HomeTests(TestCase):
def test_home_view_status_code(self):
url = reverse('home')
response = self.client.get(url)
self.assertEquals(response.status_code, 200)
def test_home_url_resolves_home_view(self):
view = resolve('/')
self.assertEquals(view.func, home)
class InspectionDefectTest(TestCase):
def setUp(self):
Inspection.objects.create(workOrderNum='312456',partNum='SD33345100-AQ1',customerName='TERRA Inc.',qtyInspected=10,qtyRejected=2)
def test_inspection_defects_view_success_status_code(self):
url = reverse('inspection_defects', kwargs={'pk': 1})
response = self.client.get(url)
self.assertEquals(response.status_code, 200)
Here is my urls.py file.
from django.conf.urls import url
from django.contrib import admin
from finalreports import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^inspections/(?P<pk>\d+)/$', views.inspection_defects, name='inspection_defects'),
url(r'^admin/', admin.site.urls),
]
Here's views.py
from django.shortcuts import render
from .models import Inspection
# Create your views here.
def home(request):
inspections = Inspection.objects.all()
return render(request, 'home.html', {'inspections': inspections})
def inspection_defects(request, pk):
inspection = Inspection.objects.get(pk=pk)
return render(request, 'topics.html', {'inspection': inspection})
Here's topics.html
{% load static %}<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{ inspection.workOrderNum }}</title>
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
</head>
<body>
<div class="container">
<ol class="breadcrumb my-4">
<li class="breadcrumb-item">Inspections</li>
<li class="breadcrumb-item active">{{ inspection.workOrderNum }}</li>
</ol>
</div>
</body>
</html>
For some reason, Django is complaining that the test.py is failing due to an unexpected keyword argument partNum.
I don't know where to look for the problem. It's getting frustrated thinking about programming all the time.
The error is Inspection() got an unexpected keyword argument partNum and I don't know where to look for the error.
In tests.py play with this instead.
class InspectionTests(TestCase):
def setUp(self):
Inspection.objects.create(workOrderNum='123DER', partNumber='sd', customerName="RYANTRONICS", qtyInspected=10, qtyRejected=3)
def test_board_topics_view_success_status_code(self):
url = reverse('inspection_topics', kwargs={'pk': 1})
response = self.client.get(url)
self.assertEquals(response.status_code, 200)
It's good to keep trying and take your time. After all, a fun project should not be rushed.
The hardest thing in Django is getting the URLs to work.

django 2 model function is not recognized inside of index.html

hey im new to django so don't be harsh !.im trying to make a blog in django . i need to map the posts in home page to the post page. for that .i have defined a function called get_absulute_url(self) in models.py but it is not recognized in index.html.
when i click on Links nothing happens...i'm not where did i made the mistake !
model.py
from django.db import models
from django.urls import reverse
import posts
# Create your models here.
class post(models.Model):
title=models.CharField(max_length=500)
content=models.TextField()
timestamp=models.DateTimeField(auto_now=False,auto_now_add=True)
updated= models.DateTimeField(auto_now=False,auto_now_add=True)
def get_absulute_url(self):
return reverse("posts:detail", kwargs={'id': self.id})
# return reverse(viewname=posts.views.posts_list,urlconf=any, kwargs={"id": self.id})
views.py
def posts_list(request):#list items
queryset=post.objects.all()
context={
"objectsList":queryset,
"title":"list"
}
return render(request,"index.html",context)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
{% for obj in objectsList %}
Link<br>
{{ obj.title }} <br>
{{ obj.content }} <br>
{{ obj.timestamp }} <br>
{{ obj.updated }} <br>
{{ obj.id }} <br>
{{ obj.pk }} <br>
{% endfor %}
</body>
</html>
url.py
from django.contrib import admin
from django.urls import path
from posts import views as posts_views
urlpatterns = [
path('create/',posts_views.posts_create),
path('<int:id>/', posts_views.posts_detail,name="detail"),
path('',posts_views.posts_list),
path('update/', posts_views.posts_update),
path('delete/', posts_views.posts_delete),
]
Change posts:detail to detail
return reverse("detail", kwargs={'id': self.id})
href="{% url "detail" id=obj.id %}"
Mapping may be the problem but it will throw error before execution.
Still add app_name = 'posts' in urls.py file of your app and try this may work or just use DetailView builtin class still getting error you better add post_detail view to the question above so we can get indepth picture of what you are looking for.

django getting error about views.py

This is my views.py
from django.shortcuts import render
from . models import Houses
def houses_list(request):
house = Houses.objects.all().order_by('owner')
return render('Houses.html',{'houses':house})
this my models.py
from django.db import models
class Houses(models.Model):
owner = models.CharField(max_length=250)
house_name = models.CharField(max_length=500)
country = models.CharField(max_length=500)
genre = models.CharField(max_length=100)
def __str__(self):
return self.house_name
class house(models.Model):
houses = models.ForeignKey(Houses, on_delete=models.CASCADE)
file_type = models.CharField(max_length=10)
house_title = models.CharField(max_length=250)
this my url.py
from django.urls import path
from . import views
urlpatterns= [
path('', views.Houses, name='Houses'),
]
this my html file
{% load static %}
<html>
<head>
<meta charset = "utf-8">
<title>Houses</title>
</head>
<body>
<h1>House list</h1>
<div class="house">
{% for house in houses %}
<div class="house">
<h2>{{Houses.house_name}}</h2>
<p>{{Houses.owner}}</p>
<p>{{Houses.genre}}</p>
</div>
{% endfor %}
</div>
</body>
</html>
I'm tring to get the data from my database but on the web getting attribute no object error.But I can see the all objects on the admin page do you have any idea what I'm doing wrong?
Here is code with fixed bugs:
The bug in urls was causing AttributeError. Fix code to:
urlpatterns= [
path('', views.houses_list, name='Houses'),
]
Remember that urls must point to views. But after you fix this, the next error will be in the views.py, because render() is missing request argument. Change to:
def houses_list(request):
house = Houses.objects.all().order_by('owner')
return render(request, 'Houses.html',{'houses':house})
The bug in the template would just render empty. Fix to:
{% for house in houses %}
<div class="house">
<h2>{{house.house_name}}</h2>
<p>{{house.owner}}</p>
<p>{{house.genre}}</p>
</div>
{% endfor %}
You are trying to get attributes from the Houses class in your template. Replace Houses with house, which is the current Houses object returned by the for loop. `
<h1>House list</h1>
<div class="house">
{% for house in houses %}
<div class="house">
<h2>{{house.house_name}}</h2>
<p>{{house.owner}}</p>
<p>{{house.genre}}</p>
</div>
{% endfor %}
</div>
EDIT
As Borut mentioned, your render call in houses_list is missing the request, i.e.
return render(request, ...)
Also, your urlpatterns is referencing Houses model instead of the houses_list view, i.e. it should be views.houses_list instead of views.Houses.

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