I'm trying to show all the data that I have saved in my admin page to users visiting my website.
models.py:
class Movie(models.Model):
name = models.CharField(max_length=255)
genre = models.CharField(max_length=255)
date_of_release=models.CharField(max_length=255)
IMDb=models.CharField(max_length=250)
cast=models.TextField(max_length=500,null=True)
summary=models.TextField(max_length=500,null=True)
image=models.TextField(max_length=500,null=True)
def __str__(self):
return self.name
I want the movie name to be shown to users and when they click on the name it takes them to another page that contain all the information about the movie.
Any ideas?
An example is below.
urls.py:
from . import views
urlpatterns=[
path('movies/', views.movies, name='movies'),
path('movies/<int:id>/',views.single_movie, name='single_movie')
]
views.py:
from django.shortcuts import get_object_or_404
def movies(request):
items = Movie.objects.all()
return render(request, 'some_folder_name/movies.html', {'movies':items})
def single_movie(request,id):
one_movie=get_object_or_404(Movie, id=id)
return render(request,'some_folder_name/single_movie.html', {'movie':one_movie})
movies.html:
<body>
{% for movie in movies %}
Name : {{movie.name}}
{% endfor %}
</body>
single_movie.html:
<body>
{% if movie %}
<h1>Information of {{movie.name}}</h1>
<p> genre: {{movie.genre}} </p>
<p> Date of release: {{movie.date_of_release}} </p>
<p> Cast: {{movie.cast}} </p>
{% endif %}
</body>
Similarly, you can show all the information of clicked movie in single.movie.html page.
Related
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
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 working on a studentresult website in Python and Django. Now I want to ask to the database to give me the names of the groups that are in the database. Using the standard db.sqlite3 database from django. In the Dropdown menu I get three white bars because I have three groups now. When I the Class DisplayGroups to id = Models.IntegerField(id, flat=True) change return.self.group_name to return self.id then the dropdownlist shows me the ID that the group has. But how can I show the name of the group. Tried a lot:
Changed to group in the model
Changed to groupname in the model
Changed a few of the commands in the views.py
Made a new database item Groepen and changed query to that.
views.py
from django.shortcuts import render, redirect
from .models import DisplayGroups, DisplayUsername
from django.contrib.auth.models import User, Group
def index(request):
response = redirect('/login')
return response
def home(response):
return render(response, "home/home.html")
def bekijk(request):
DisplayGroup = Group.objects.all()
print(DisplayGroup)
DisplayNames = User.objects.all()
print(DisplayNames)
return render(request, "home/bekijk.html", {"DisplayGroups": DisplayGroup,"DisplayUsername":DisplayNames})
models.py
from django.db import models
# Create your models here.
class DisplayGroups(models.Model):
group_name = models.CharField(max_length=200)
def __str__(self):
return self.group_name
class DisplayUsername(models.Model):
username = models.CharField(max_length=100)
def __str__(self):
return self.username
The html page
{% extends 'home/base.html' %}
{% block title %}Cijfers studenten{% endblock %}
{% block javascript %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
var $productvar=$("#groupdd1");
$itemvar=$("#userdd1");
$options=$itemvar.find('option');
$productvar.on('change', function()
{
$itemvar.html($options.filter('[value="'+this.value+'"]'))
}).trigger('change');
});
</script>
{% endblock %}
{% block content %}
<h1>Studentresultaten</h1>
<select id="groupdd1">
<option disabled="true" selected>-- Select Fruit --</option>
{% for result in DisplayGroups %}
<option>{{result.group_name}}</option>
{% endfor %}
</select>
<select id="userdd1">
<option disabled="true" selected>-- Select Fruit --</option>
{% for result in DisplayUsername %}
<option>{{result.username}}</option>
{% endfor %}
</select>
{% endblock %}
The piece of jquery is for later, because I want to make a dependant dropdown menu. Hope you guys can help me. Thanks in advance!
#WilliamVanOnsem is right the model from where you are filtering is Group which do not have group_name as a field. Here's what you can do.
In views.py
DisplayGroup = DisplayGroups.objects.all()
DisplayNames = DisplayName.objects.all()
Now in HTML template you can access group_name and result.username. The User model has username field so result.username did not show an empty text
I have created a class in the models.py containing the information of articles I want to insert in a website
from django.db import models
from django.urls import reverse
class Article(models.Model):
"""
Model representing an article.
"""
title = models.CharField(max_length=200)
authors = models.CharField(max_length=200)
summary = models.TextField(max_length=1000, help_text='Enter a brief description of the article')
content = models.TextField(max_length=100000)
def __str__(self):
"""
String for representing the Model object.
"""
return self.title
def get_absolute_url(self):
"""
Returns the url to access a detail record for this article.
"""
return reverse('article-detail', args=[str(self.id)])
After that, I have inserted an article using the admin panel of Django and saved it.
Then, I have created the index.html shown below calling the articles in the database
<!DOCTYPE html>
<html lang="en">
<head>
{% block title %}{% endblock %}
</head>
<body>
{% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
{% block content %}<!-- default content text (typically empty) -->
<!-- Articles -->
<div class="articles">
<h1>Titolo: {{ article.title }}</h1>
<p><strong>Autori:</strong> {{ article.authors }}</p>
<p><strong>Riepilogo:</strong> {{ article.summary }}</p>
<p><strong>Testo:</strong> {{ article.content }}</p>
</div>
{% endblock %}
</body>
</html>
But the article is not shown despite being in the database (see prints below)
EDIT1: inserted views.py as requested
from django.shortcuts import render
from .models import Article
# Create your views here.
def index(request):
"""
View function for home page of site.
"""
# Render the HTML template index.html with the data in the context variable
return render(
request,
'index.html',
)
You are not including any articls in your template context:
return render(
request,
'index.html',
)
You could include the articles in the template context with:
articles = Article.objects.all()
return render(
request,
'index.html',
{'articles': articles}
)
Then in the template you need to loop through the articles.
<!-- Articles -->
<div class="articles">
{% for article in articles %}
<h1>Titolo: {{ article.title }}</h1>
<p><strong>Autori:</strong> {{ article.authors }}</p>
<p><strong>Riepilogo:</strong> {{ article.summary }}</p>
<p><strong>Testo:</strong> {{ article.content }}</p>
{% endfor %}
</div>
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.