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.
Related
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.
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
i am making like a demo website that sells fruits i am following a youtube tutorial by (code with mosh) his images loaded properly but my images wont other things like add to cart button and name of product loaded properly. I am very new to programming so please try not to use complex programming terms for answer and thanks to anyone who will be trying to help me.
admin.py
from django.contrib import admin
from .models import Product, Offer
class OfferAdmin(admin.ModelAdmin):
list_display = ('code', 'discount')
class ProductAdmin(admin.ModelAdmin):
list_display = ('name', 'price', 'stock')
admin.site.register(Product, ProductAdmin)
admin.site.register(Offer, OfferAdmin)
apps.py
from django.apps import AppConfig
class ProductsConfig(AppConfig):
name = 'products'
models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=255)
price = models.FloatField()
stock = models.IntegerField()
image_url = models.CharField(max_length=2083)
class Offer(models.Model):
code = models.CharField(max_length=10)
description = models.CharField(max_length=255)
discount = models.FloatField()
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('new', views.new)
]
views.py
from django.http import HttpResponse
from django.shortcuts import render
from .models import Product
def index(request):
products = Product.objects.all()
return render(request, 'index.html',
{'products': products})
def new(request):
return HttpResponse('New products')
index.html
{% extends 'base.html' %}
{% block content %}
<h1>Products</h1>
<div class="row">
{% for product in products %}
<div class="col">
<div class="card" style="width: 18rem;">
<img src="..." class="{{ product.image_url}}" alt="...">
<div class="card-body">
<h5 class="card-title">{{ product.name }}</h5>
<p class="card-text">{{ product.price }}₹</p>
Add to cart
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
This line is your problem:
<img src="..." class="{{ product.image_url}}" alt="...">
The class is an attribute which specifies one or more class names for an HTML element, which will be the img element in this case. The class name can be used by CSS and JavaScript to perform certain tasks for elements with the specified class name. Therefore, in this case, the class value should not be a dynamic value as the class attribute is not used to display information.
The src attribute is used to specify the URL of the source image
<img src="{{ product.image_url}}" alt="...">
I am a beginner in Django. I am building a Django app, named PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models.
I have already created models and views. I have also managed to add clickable link in the first template (brandlist.html). In the first template, when you click on the brand name, like Samsung, you will be taken to the page of the phone model, like Galaxy S10.
Here is the screenshot of the first template:
When you click the link, you will be taken to the second template (phonemodel.html). But now, I am facing an issue. There is no clickable link on the phone model ("Galaxy S10") that will direct you to details.html. Here is the screenshot.
Here are the codes of models.py inside the "PhoneReview" folder:
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Brand(models.Model):
brand_name = models.CharField(max_length=100)
origin = models.CharField(max_length=100)
manufacturing_since = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return self.brand_name
def save(self, *args, **kwargs):
self.slug = slugify(self.brand_name)
super().save(*args, **kwargs)
class PhoneModel(models.Model):
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
model_name = models.CharField(max_length=100)
launch_date = models.CharField(max_length=100)
platform = models.CharField(max_length=100)
def __str__(self):
return self.model_name
class Review(models.Model):
phone_model = models.ManyToManyField(PhoneModel, related_name='reviews')
review_article = models.TextField()
date_published = models.DateField(auto_now=True)
slug = models.SlugField(max_length=150, null=True, blank=True)
def __str__(self):
return self.review_article
Here are the codes of urls.py inside the "PhoneReview" folder:
from . import views
from django.urls import path
urlpatterns = [
path('index', views.BrandListView.as_view(), name='brandlist'),
path('phonemodel/<int:pk>/', views.ModelView.as_view(), name='modellist'),
path('details/<int:pk>/', views.ReviewView.as_view(), name='details'),
]
Here are the codes of views.py inside the "PhoneReview" folder:
from django.views import generic
from .models import Brand, PhoneModel, Review
class BrandListView(generic.ListView):
template_name = 'PhoneReview/brandlist.html'
context_object_name = 'all_brands'
def get_queryset(self):
return Brand.objects.all()
class ModelView(generic.DetailView):
model = PhoneModel
template_name = 'PhoneReview/phonemodel.html'
class ReviewView(generic.DetailView):
model = Review
template_name = 'PhoneReview/details.html'
Here are the codes of apps.py inside the "PhoneReview" folder:
from django.apps import AppConfig
class PhonereviewConfig(AppConfig):
name = 'PhoneReview'
Here are the codes of details.html inside the "templates" folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
<html>
<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">
<html lang="en">
{% block title%}Details{% endblock %}
{% block content %}
<h1>This is the Details Page</h1>
<h2>Review:</h2>
<p>{{ review.review_article }}</p>
<h2>News Link:</h2>
<p>{{ review.slug }}</p>
{% endblock %}
</html>
Here are the codes of phonemodel.html inside the "templates" folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
{% block title%}
Phone Model Page
{% endblock %}
{% block content %}
<!--Page content-->
<h1>This is Phone Model Page</h1>
<h2>Here is the phone model</h2>
<ul>
<li>{{ phonemodel.model_name }}</li>
</ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}
I tried replacing <li>{{ phonemodel.model_name }}</li> with <li>{{ phonemodel.model_name }}</li>. But I get an error, which looks like this:
NoReverseMatch at /phonemodel/1/
Reverse for 'details' with arguments '('',)' not found. 1 pattern(s) tried: ['details/(?P<pk>[0-9]+)/$']
How can I fix the issue?
There is no context variable named brand and you don't need it anyway. You should use the id of the phonemodel:
<li>
<a href = "{% url 'details' phonemodel.id %}">
{{ phonemodel.model_name }}
</a>
</li>
I wanna make a page which shows POST's models' contents is shown each category.For example, when I put Python link in in detail.html,only POST's models' contents with Python's category is shown in category.html.When I put Python link in category.html,I got an error,ImproperlyConfigured at /app/category/Python/ CategoryView is missing a QuerySet. Define CategoryView.model, CategoryView.queryset, or override CategoryView.get_queryset(). I wrote codes in views.py
def top(request):
content = POST.objects.order_by('-created_at')[:5]
category_content = Category.objects.order_by('-created_at')[:5]
page = _get_page(blog_content, request.GET.get('page'))
return render(request, 'top.html',{'content':content,'category_content':category_content,"page":page})
class CategoryView(BaseListView):
template_name = 'category.html'
def get_queryset(self):
category_name = self.kwargs['category']
self.category = Category.objects.get(name=category_name)
queryset = super().get_queryset().filter(category=self.category)
return queryset
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['category'] = self.category
return context
in urls.py
urlpatterns = [
path('top/', views.top, name='top'),
path('category/<str:category>/',views.CategoryView.as_view(), name='category'),
]
in models.py
class Category(models.Model):
name = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
class POST(models.Model):
title = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
def __str__(self):
return self.title
in top.html
<div class="list-group">
<a href="#">
Category
</a>
<div>
{% for category in category_content %}
<a href="{% url 'category' category.name %}">
{{ category.name }}
</a>
{% endfor %}
</div>
</div>
in category.html
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Category</title>
</head>
<body>
<div>
{% for content in queryset %}
<h2>{{ content.title }}</h2>
<img src="content.image.url" />
<a class="btn btn-outline-primary btn-lg btn-block" href="{% url 'detail' content.pk %}">SHOW DETAIL</a>
{% endfor %}
</div>
<div>
<a href="#" class="list-group-item active">
Category
</a>
<div>
{% for category in category_content %}
<a class="list-group-item justify-content-between" href="{% url 'category' category.name %}">
{{ category.name }}
</a>
{% endfor %}
</div>
</div>
</body>
</html>
I really cannot understand why ImproperlyConfigured which means settings.py is wrong.When I changed BaseListView into ListView,same error happens.I wrote get_queryset in CategoryView's class so I cannot understand codes needs QuerySet. How should I fix this?What is wrong in my codes?
One issue is that you're calling super().get_queryset(), which expects your class to define a queryset or a model. Adding model = Category will fix that error.
It looks like you're returning a queryset with just one entry, though. If you only want to get the one category, it would be simpler to use a DetailView:
from django.views.generic import DetailView
from .models import Category # or wherever it is
class CategoryView(DetailView):
model = Category
template_name = 'category.html'
def get_object(self):
category_name = self.kwargs['category']
return Category.objects.get(name=category_name)
Note that your template would need to be updated to reference category or object instead of looping through the queryset.