I have 2 models named "developer" and "skill". I made a page for all the developers that have their respective information. Now, I want to make a page that lists all the developers with links that navigate to their respective information page.
The page that shows all the developers' URLs is 'developers/' and its name is "developers". The URL of the second page is 'developers/id' and its name is developer, however it instead navigates to 'developers/developers/id'.
I tried the page that shows the information of a certain developer and it was ok but I have problem with this one cause it won't navigate.
here are my codes :
views.py
from django.shortcuts import render
from .models import Developer, Skill
# Create your views here.
def show_developers(request):
query = Developer.objects.all()
context = {'devs': query}
return render(request, 'users/devs.html', context=context)
def show_single_developer(request, pk):
query = Developer.objects.get(id=pk)
context = {'dev': query}
return render(request, 'users/single_dev.html', context=context)
models.py
from django.db import models
# Create your models here.
class Skill(models.Model):
choices = (
('Beginner', 'Beginner'),
('Junior', 'Junior'),
('Senior', 'Senior'),
)
name = models.CharField(max_length=50)
level = models.CharField(choices=choices, max_length=10)
class Developer(models.Model):
full_name = models.CharField(max_length=50)
username = models.CharField(max_length=50)
intro = models.TextField(blank=True, null=True)
image = models.ImageField()
skills = models.ForeignKey(Skill, on_delete=models.CASCADE)
urls.py
from django.urls import path
from .views import show_developers, show_single_developer
urlpatterns = [
path('developers/', show_developers, name='developers'),
path('developers/<str:pk>/', show_single_developer, name='developer'),
]
devs.html
{% include 'navbar.html' %}
<table>
<tr>
<th>FullName</th>
<th>Username</th>
<th>details</th>
</tr>
{% for dev in devs %}
<tr>
<td>{{dev.full_name}}</td>
<td>{{dev.username}}</td>
<td>View</td>
</tr>
{% endfor %}
</table>
{% include 'footer.html' %}
single_dev.html
{% include 'navbar.html' %}
<h2>{{dev.full_name}}</h2>
<hr>
<h3>Intro</h3>
<h4>{{dev.intro}}</h4>
{% for skill in dev.sills.all %}
<div>
<p>{{skill.name}}</p>
<p>{{skill.level}}</p>
</div>
{% endfor %}
{% include 'footer.html' %}
TraceBack Section
and I add the structures of this app too
Error page
Related
I have data being stored in a Django model, and I want to display that data in my HTML file. What is the easiest way that I could do this? I am familiar with [this][1] question, but it does not help me because it is not very detailed and does not have a definite answer. Can someone please help me? My code is down below.
Django Model:
class userdetails(models.Model):
donations = models.IntegerField(blank=True, null = True,)
points = models.IntegerField(blank=True, null = True,)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
blank=True,
null=True,
)
HTML where I want to display data from the model:
<div class="box">
<span class="value"> </span>
<span class="parameter">Points</span>
</div>
This is my view:
#login_required(login_url='/login/')
def dashboard(request):
id = request.user.id
data= userdetails.objects.get(id=id)
return render(request,'dashboard.html',{'data':data})
The error I keep getting:
DoesNotExist at /dashboard/
userdetails matching query does not exist.
Has something to do with data= userdetails.objects.get(id=id) in my views.
you need to create a view to retreive the data you need from your model :
views.py :
from .models import userdetails
from django.shortcuts import render
def get_data(request):
my_data = userdetails.objects.all() #for all the records
one_data = userdetails.objects.get(pk=1) # 1 will return the first item change it depending on the data you want
context={
'my_data':my_data,
'one_data':one_data,
}
return render(request, 'get_data.html', context)
add the the view to urls.py :
url.py :
from .views import get_data
urlpatterns = [
path('get_data/', get_data, name='get_data'),
]
create get_data.html in the templates folder :
get_data.html : for the list
{% block content %}
{% for x in my_data %}
{{x.name }}
{% endfor %}
{% endblock content %}
for the item :
{% block content %}
{{one_data}}
{% endblock content %}
the best practice is to create a list view and a detail view so if you dont know how tell me and i will show you
You need to add a function to the views.py file and render the HTML file to a URL that should be there in Url Patterns.
For example:
This is a sample model:
class C(models.Model):
name = models.CharField(max_length=125, null=True)
phone = models.CharField(max_length=125, null=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
This is my views.py
from .models import *
def home(request):
c = C.objects.all()
return render(request, "<app_name>/index.html", {'c': c})
This is my urls.py
from . import views
urlpatterns = [
path('home/',views.home),
]
This is my part of HTML file where I will show the data
{% block content %}
<h2>{{c.name}}</h2>
{% endblock content %}
EDIT: Fixed it! in models.py I had to add this to point it to the right table as it uses the folder name as a prefix.
class Meta:
managed = False
db_table = 'tablename'
I'm looking to display the contents of a postgres table in Django. Clearly I'm doing something wrong but can not figure out why the data won't show.
Below is what I have so far, the tables headers show but there is no data or any error messages. Checked the table in pgAdmin and there is plenty of data there.
# models.py
from django.db import models
from datetime import datetime
# Create your models here.
class SensorData(models.Model):
device_name = models.TextField()
sensor_type = models.TextField()
sensor_data = models.SmallIntegerField()
sensor_date = models.DateTimeField()
def __str__(self):
return self.device_name
# views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import ListView
from .models import SensorData
# Create your views here.
class ErrorView(ListView):
model = SensorData
template_name = 'errors.html'
# urls.py
from django.urls import path
from .views import ErrorView
urlpatterns = [
path('errors/', ErrorView.as_view(), name='errors'),
path('', ErrorView.as_view(), name='errors'),
]
# errors.html
{% extends 'layout.html' %}
{%block content %}
<section class ='infoContainer'>
<div id = 'sensorInfo'>
<h2> Error Information </h2>
<table id = "deviceTable">
<tr>
<th><strong>Device </strong></th>
<th><strong>Sensor Type </strong></th>
<th><strong>Date</strong></th>
<th><strong>Information</strong></th>
</tr>
{% for error in object_list %}
<tr>
<td> {{error.device_name}} </td>
<td> {{error.sensor_type}} </td>
<td> {{error.sensor_date}} </td>
<td> {{error.sensor_data}} </td>
</tr>
{% endfor %}
</table>
</div>
</section>
{% endblock content %}
First of all sorry for my bad english but i'm french.
I am currently working on a django app and i'm trying to make my HTML page work but it won't and i dont know why.
I followed the tutoriel but i edited some of the code to fit my purpose. And now my page won't print out my variable.
I have python 2.7.5 and Django 1.11.29
My html page
Now this is my code for the HTML :
{% if True %}
<p> Vrai </p>
<li>{{ Thriller.title }}</li>
{% else %}
<p> faux </p>
{% endif %}
<ul>
<p> Paragraphe : </p>
<li>{{ Thriller.title }}</li>
<li>{{ Thriller.id }}</li>
</ul>
My code for the Django part :
This is in the models.py file :
from django.db import models
import datetime
from django.utils.encoding import python_2_unicode_compatible
from django.utils import timezone
class Artist(models.Model):
name = models.CharField(max_length=200, unique=True)
def __str__(self):
return self.name
class Album(models.Model):
reference = models.IntegerField(null=True)
created_at = models.DateTimeField(auto_now_add=True)
available = models.BooleanField(default=True)
title = models.CharField(max_length=200, unique=True)
picture = models.URLField()
artists = models.ManyToManyField(Artist, related_name='albums', blank=True)
def __str__(self):
return self.title
This is in the views.py file :
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
from .models import Album, Artist, Contact, Booking
from django.template import loader
def index(request):
albums = Album.objects.order_by('-created_at')
context = {'albums = ': albums}
template = loader.get_template('polls/index.html')
return HttpResponse(template.render(context, request))
This is also my first post here and i dont really know if the post is good or not so forgive it if it's not good !
You can ask me anything you want. Thank's !
You need to call your context variable in the template instead of {{ Thriller.title }} because you did not specify Thriller in the context of your view.
Your context in the index() view:
context = {'albums = ': albums}
Edit this to:
context = {'albums': albums}
and then in your template, for example to loop over all the album titles:
added the if statement:
{% for album in albums %}
{% if album.title == "Thriller" %}
<p>{{ album.title }}</p>
{% endif %}
{% endfor %}
Try this change to your context
context = {'albums': albums}
Then in your template do...
{% for album in albums %}
<p>{{ album.title }}</p>
{% endfor %}
I am trying to create webpages that link to each other with Django. I created a model with several elements: title, summary, description01, description02. On the first page, the home page, I display the title and summary, this seems to work fine. However, I want a link after the title and summary that links to a page with description01 and then a link to a page with description02. This is where I am having issues. I created a file for description01.html, I created a function for it in views.py, a path in urls.py, and added a link to home. When I try to open the home page, I get error: NoReverseMatch at /
Reverse for 'description01' with arguments '(3,)' not found. 1 pattern(s) tried: ['articles/$']
Code and Screenshots:
home.html
<h1>home</h1>
{% for outline in outline %}
{{ outline.title }}<br>
{{ outline.summary }}<br>
LInk
{% endfor %}
viwes.py
from django.shortcuts import render
from .models import Outline
def home(request):
outline = Outline.objects.all()
return render(request, 'articles/home.html', {'outline': outline})
def description01(request):
outline = Outline.description01
return render(request, 'articles/description01.html', {'outline': outline})
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from articles import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('articles/', views.description01, name='description01'),
]
models.py
from django.db import models
class Outline(models.Model):
title = models.CharField(max_length=100)
summary = models.CharField(max_length=250, default="")
description01 = models.CharField(max_length=250, default="")
description02 = models.CharField(max_length=250, default="")
description01.html
<h1>description01</h1>
{% for outline in outline %}
{{ outline.description01 }}<br>
{% endfor %}
enter image description here
{% for outline in outline %} may give you an error, because you could be calling the inner outline or the global one. Try changing it to:
{% for otlne in outline %}
{{ otlne.description01 }}<br>
{% endfor %}
Also, there is probably something wrong with outline = Outline.description01, don't you mean:
def description01(request):
outline_objs = Outline.objects.all()
context = {
'd_01': [outline.description01 for outline in outline_objs]
}
return render(request, 'articles/description01.html', context=context)
and then:
{% for d in d_01 %}
{{ d }}<br>
{% endfor %}
This way, the d_01 key that would be accessed in the HTML files would be only a list of the description01 in all Outlines objects.
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.