Image link does not work when parts are retrieved from API - python

I write a project of a list of films with their details(IMDB). When I click on the image of a film he doesn't go to the page of that film. I do not understand where the problem is in url on html file or in the models?
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/movies/%7B$%20url%20'movies:movie_detail'%20movie.slug%20%25%7D
Using the URLconf defined in django_movie_center.urls, Django tried these URL patterns, in this order:
admin/
movies/ [name='movie_list']
movies/ category/<str:category> [name='movie_category']
movies/ language/<str:lang> [name='movie_language']
movies/ search/ [name='movie_search']
movies/ <slug:slug> [name='movie_detail']
movies/ year/<int:year> [name='movie_year']
^static/(?P<path>.*)$
^media/(?P<path>.*)$
The current path, movies/{$ url 'movies:movie_detail' movie.slug %}, didn't match any of these.
models.py:
from django.db import models
from django.utils.text import slugify
# Create your models here.
CATEGORY_CHOICES = (
('action','ACTION'),
('drama','DRAMA'),
('comedy','COMEDY'),
('romance','ROMANCE'),
)
LANGUAGE_CHOICES = (
('english','ENGLISH'),
('german','GERMAN'),
('hebrew','HEBREW')
)
STATUS_CHOICES = (
('RA' , 'RECRNTLY ADDED'),
('MW' , 'MOST WATCHED'),
('TR' , 'TOP RATED'),
)
class Movie(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(max_length=1000)
image = models.ImageField(upload_to='movies')
category = models.CharField(choices=CATEGORY_CHOICES , max_length=10)
language = models.CharField(choices=LANGUAGE_CHOICES, max_length=10)
status = models.CharField(choices=STATUS_CHOICES, max_length=2)
cast = models.CharField( max_length=100)
year_of_production = models.DateField()
views_count = models.IntegerField(default=0)
movie_trailer = models.URLField()
slug = models.SlugField(blank=True, null=True)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Movie, self).save(*args, **kwargs)
def __str__(self):
return self.title
LINK_CHOICES = (
('D','DOWNLOAD LINK'),
('W','WATCH LINK'),
)
class MovieLink(models.Model):
movie = models.ForeignKey(Movie, related_name='movie_watch_link', on_delete=models.CASCADE)
type = models.CharField(choices=LINK_CHOICES , max_length=1)
link = models.URLField()
def __str__(self):
return self.movie
app_url:
from django.urls import path
from .views import MovieList , MovieDetail , Movie_Category , Movie_Language , Movie_Serch , Movie_Year
app_name = 'movie center'
urlpatterns = [
path('', MovieList.as_view() , name='movie_list'),
path('category/<str:category>', Movie_Category.as_view() , name='movie_category'),
path('language/<str:lang>', Movie_Language.as_view() , name='movie_language'),
path('search/', Movie_Serch.as_view() , name='movie_search'),
path('<slug:slug>', MovieDetail.as_view() , name='movie_detail'),
path('year/<int:year>', Movie_Year.as_view() , name='movie_year'),
The error is in class="movies" in
html_list_of_the_project:
{% extends 'base.html' %}
{% block body %}
<main class="content">
<section class="centered">
{% if movie_category %}
<h3>{{movie_category|title}} Movies</h3>
{% endif %}
{% if movie_language %}
<h3>{{movie_language|title}} </h3>
{% endif %}
<div class="movies">
{% for movie in object_list %}
<div class="mov">
<a href="{$ url 'movies:movie_detail' movie.slug %}">
<img src="{{movie.image.url}}">
<h2 class="movietitle">{{movie.title}}</h2>
</a>
</div>
{% empty %}
<h3>This Category Is Empty !</h3>
{% endfor %}
</div>
{% if is_paginated %}
<nav class="pagination">
<ul>
{% if page_obj.has_previous %}
<li>Prev</li>
{% else %}
<li class="disabled"></li>
{% endif %}
{% for pages in page_obj.paginator.page_range %}
{% if page_obj.number == pages %}
<li>{{pages}} </li>
{% else %}
<li>{{pages}} </li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li>Next</li>
{% else %}
<li class="disabled"></li>
{% endif %}
</ul>
</nav>
{% endif %}
</section>
</main>
{% endblock body %}

You have a typo "$" in the URL mentioned on the a-tag written in the movie for-loop
<a href="{$ url 'movies:movie_detail' movie.slug %}">
<img src="{{movie.image.url}}">
The URL should be like this: {% url 'movies:movie_detail' movie.slug %}

Related

get_object_or_404() got an unexpected keyword argument 'slug'

TypeError at /vegetables/
get_object_or_404() got an unexpected keyword argument 'slug'
views.py
from django.shortcuts import render, get_object_or_404
from .models import Category
from .models import Product
def allProductCategory(request,c_slug=None):
c_page=None
products=None
if c_slug!=None:
c_page=get_object_or_404(Category,slug=c_slug)
products=Product.objects.all().filter(category=c_page,available=True)
else:
products=Product.objects.all().filter(available=True)
return render(request, 'category.html',{'category':c_page,'products':products})
urls.py
app_name='ecommerceapp'
urlpatterns = [
path('',views.allProductCategory,name='allProductCategory'),
path('<slug:c_slug>/',views.allProductCategory,name='products_by_category'),
]
Includes 2 tables-Category, Product
models.py
class Category(models.Model):
name = models.CharField(max_length=250,unique=True)
slug = models.SlugField(max_length=250,unique=True)
desc = models.TextField(blank=True)
image = models.ImageField(upload_to='category',blank=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return '{}'.format(self.name)
def get_url(self):
return reverse('ecommerceapp:products_by_category',args=[self.slug,])
class Product(models.Model):
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
desc = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
image = models.ImageField(upload_to='product', blank=True)
stock = models.IntegerField()
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('name',)
verbose_name = 'product'
verbose_name_plural = 'products'
def __str__(self):
return '{}'.format(self.name)
Base.html is created. header.html, navbar.html, footer.html are included in base.html. Other than these three a block content and endblock is created in base.html.
category.html
{% extends 'base.html' %}
{% load static %}
{% block metadescription %}
{% if category %}
{{ category.description|truncatewords:155 }}
{% else %}
Welcome to ZUPER Store where you can get everything.
{% endif %}
{% endblock %}
{% block title %}
{% if category %}
{{ category.name }} - ZUPER store
{% else %}
All that you need - ZUPER store
{% endif %}
{% endblock %}
{% block content %}
{% if category %}
<div>
<div>
<p>Our products</p>
</div>
</div>
{% endif %}
<div>
{% if category %}
<img src="{{category.image.url}}" alt="{{category.name}}">
</div>
<br>
<div>
<h1>{{category.name}}</h1>
<p>{{category.description}}</p>
</div>
{% else %}
<div>
<img src="{% static 'images/Banner.png' %}" alt="Our products" width="500px;" height="100px;">
</div>
<br>
<div>
<h1>Our product collections</h1>
<p>Dummy content</p>
</div>
{% endif %}
<div>
<div>
{% for product in products %}
<div>
<div>
<img src="{{product.image.url}}" alt="{{product.name}}">
<div>
<h4>{{product.name}}</h4>
<p>{{product.price}}</p>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
I'am getting this error when I click on the hyperlink vegetables and cotton dress.

How to create a Class Based Views search bar on Django

I'm making a search bar in Django using Class-Based Views on my Views.py. When I try to get the value submitted in the input it's not showing the query name and if I don't submit anything is NOT giving me an error. Also what is the way to get the post showed by the world searched? Thanks for all. My code is:
Models.py:
class Post(models.Model): # Post core
title = models.CharField(max_length=299)
author = models.ForeignKey(User,default=ANONYMOUS_USER_ID, on_delete=models.CASCADE)
category = models.CharField(max_length=50)
image = models.ImageField(blank=True)
desc = models.TextField()
text = RichTextField(blank = True, null = True )
date = models.DateTimeField(auto_now=False, auto_now_add=True)
slug = models.SlugField(null = True, blank = True, unique=True)
class Meta: # Order post by date
ordering = ['-date',]
def __str__(self): # Display title
return self.title
def get_absolute_url(self): # #TODO da cambiare
return reverse("listpost")
Views.py:
class SearchView(TemplateView):
model = Post
template_name = "admin/search.html"
def get(self, request, *args, **kwargs):
q = request.GET.get('q', '')
self.results = Post.objects.filter(text__icontains=q, desc__icontains = q, title__icontains = q)
return super().get(request, *args, **kwargs)
Urls.py:
path('dashboard/listpost/search/', SearchView.as_view(), name="search")
ListPost.html:
{% extends "admin/layout.html" %}
{% block title %}
<title>Post List</title>
{% endblock title %}
{% block content %}
<form action="{% url 'search' %}" method="GET">
<input type="text" placeholder="Cerca" name="search"> <button>Cerca</button>
</form>
<div class="postlist">
<div class="cards"> <!-- Card Container -->
{% for post in object_list %}
<div class="card"> <!-- Single Card -->
{% if post.image %}
<img src="{{post.image.url}}" alt="">
{% endif %}
<h3>{{ post.title }}</h3>
<p>
{{ post.category }}
{{ post.author }}
<data class="data"> {{ post.date|date:'d-m-Y' }} </data>
</p>
<p class="desc-list">{{ post.desc|truncatewords:10 }}</p>
edit
delate
</div>
{% endfor %}
</div>
</div>
{% endblock content %}
Search.html
{% extends "admin/layout.html" %}
{% block title %}
<title>Search</title>
{% endblock title %}
{% block content %}
{% if query %}
{{Query}}
{% else %}
<p>Nope</p>
{% endif %}
{% endblock content %}
Your are trying to display the variable query, Query (two different variables since the template language is case sensitive).
Your do not pass any of those two variables in the template context.
I don't see any query nor Query variable in your view.
It seems that your want to show the results variable, so I will assume this.
Your need to send the results from your queryset in the template results.
The get_context_data method ContextMixin (one of the TemplateView derived classes) is useful for this.
class SearchView(TemplateView):
model = Post
template_name = "admin/search.html"
def get(self, request, *args, **kwargs):
q = request.GET.get('q', '')
self.results = Post.objects.filter(text__icontains=q, desc__icontains = q, title__icontains = q)
return super().get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""Add context to the template"""
return super().get_context_data(results=results, **kwargs)
And in your template:
{% extends "admin/layout.html" %}
{% block title %}
<title>Search</title>
{% endblock title %}
{% block content %}
{% if results.exists %}
{% for result in results %}
{{ result }}
{% endfor %}
{% else %}
<p>Nope</p>
{% endif %}
{% endblock content %}

post_detail() view missing required positional arguments:

I'm beginner to django . I am facing this problem that I can't get the post detail view with year , month and post .
Error is post_detail() missing 4 required positional arguments: 'year', 'month', 'day', and 'post'.
this is models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class Post(models.Model):
STAUTS_CHOICE = ( ('draft','Draft'),('published','Published'),)
title =models.CharField(max_length =250)
slug = models.SlugField(max_length =250)
author = models.ForeignKey(User,related_name='blog_post')
body = models.TextField()
publish =models.DateTimeField(default = timezone.now)
created = models.DateTimeField(auto_now_add=True)
udated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length =250 ,
choices = STAUTS_CHOICE , default = 'draft')
class Meta:
ordering = ('-publish',)
def get_absolute_url(self):
return reverse('blog:post_detail', args = [self.slug, self.publish.year , self.publish.strftime('%m'), self.publish.strftime('%d')]])
def __str__(self):
return self.title
______________________________________________________________
this is views.py
from django.shortcuts import render , get_object_or_404
from .models import Post
def post_list(request):
post = Post.objects.all()
return render(request,'blog/post/list.html',{'post':post})
def post_detail(request,slug,year, month,day,post):
post = get_object_or_404(Post, slug = slug , status = 'published' ,publish_year = year, publish_month = month , publish_day = day)
return render(request,'blog/post/detail.html',{'post':post})
this is urls.py
from django.conf.urls import url
from .import views
urlpatterns = [
url(r'^post_list',views.post_list,name ='post_list'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'r'(?P<slug>[-\w]+)/$',views.post_detail,name='post_detail'),
this is post_detail.html page
{% extends 'blog/base.html' %}
{% block title %}Post details{% endblock %}
{% block content %}
<h2><a>{{post.title}}</a></h2>
<p class="date">published {{ post.published}} by {{ post.author}}</p>
{{ post.body|linebreaks }}
{% endblock %}
this is list.html page :
{% extends 'blog/base.html' %} {% block head_title %}Posts list{% endblock %}
{% block content %}
<h1>My Blog</h1>
{% for x in posts %}
<h2>
{{x.title}}
</h2>
<p class="date">published {{ x.published}} by {{ x.author}}</p>
{{ x.body|truncatewords:30|linebreaks }} {% endfor %} {% endblock %}
this is base.html
{% load staticfiles %}
<!DOCTYPE html>
<head>
<title>{% block head_title %}Welcome to my blog{% endblock %}</title>
<!-- <link rel="stylesheet" href=""> -->
</head>
<body>
<div id="sidebar">
<h1></h1>
</div>
<div id="content">
{% block content %} {% endblock %}</div>
</body>
</html>
So far I guessed you want to resolve domain/year/month/day/slug URL.
The following changes will make it work.
views.py
def post_detail(request,slug,year, month,day):
post = get_object_or_404(Post, slug = slug , status = 'published' ,publish__year = year, publish__month = month , publish__day = day)
return render(request,'blog/post/detail.html',{'post':post})
urls.py
urlpatterns = [
url(r'^post_list',views.post_list,name ='post_list'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$',views.post_detail,name='post_detail'),
]
remove post parameter from post_detail view. and remove third url for same view. Now your requested url should be:
localhost:8000/2017/12/16/my-post

Django post not showing on homepage, but in category list

I made a blog with Django. The blog lets the admin create posts and categories. I used bootstrap to align the posts next to each other.
This is the homepage of my blog. When the posts reach the other end of the screen. look at the Example below:
post1 post2 post3 post4 post5 post6 post7 post8 post9 post10 post11 post12 post 13 post14 post16.
post 16 wouldnot show on the homepage, but if you go to its category it will show on the category list but not on the homepage which is index.html
index.html
{% extends 'base.html' %}
{% block content %}
{% if categories %}
<div class="tab">
{% for category in categories %}
<button class="tablinks"><a href="{{ category.get_absolute_url }}">{{
category.title }}</a></button>
{% endfor %}
{% else %}
<p>There are no posts.</p>
{% endif %}
</div>
<br><br><br>
<div class="container ">
{% if posts %}
<div class="row ">
{% for post in posts %}
<div class="poosts col-md-2">
<p class="past"><a class="link" href="{{ post.get_absolute_url }}"><span
class="tda"> {{post.title}}</span><br><br><span class="postbody">
{{post.body|truncatewords:13}}</a></span></p>
</div>
{% endfor %}
{% else %}
<p class="text-center">There are no posts.</p>
</div>
{% endif %}
</div>
{% endblock %}
categories page
{% extends 'base.html' %}
{% block head_title %}Viewing category {{ category.title }}{% endblock %}
{% block title %}{{ category.title }}{% endblock %}
{% block content %}
<br><br><br>
<div class="container">
{% if posts %}
<div class="row">
{% for post in posts %}
<div class="poosts col-md-4">
<p class="past"><a class="link" href="{{ post.get_absolute_url }}"><span
class="tda"> {{post.title}}</span><br><br>{{post.body|truncatewords:13}}</a>
</p>
</div>
{% endfor %}
{% else %}
<p class="text-center">There are no posts.</p>
</div>
{% endif %}
</div>
{% endblock %}
views.py
from django.shortcuts import render, redirect, get_list_or_404
from django.http import HttpResponse
from .models import Blog, Category
from django.shortcuts import render_to_response, get_object_or_404
def index(request):
return render_to_response('account/index.html', {
'categories': Category.objects.all(),
'posts': Blog.objects.all()[:5]
})
def view_post(request, slug):
return render_to_response('account/view_post.html', {
'post': get_object_or_404(Blog, slug=slug)
})
def view_category(request, slug):
category = get_object_or_404(Category, slug=slug)
return render_to_response('account/view_category.html', {
'category': category,
'posts': Blog.objects.filter(category=category)[:5]
})
models.py
from django.db import models
from django.db.models import permalink
class Blog(models.Model):
title = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
body = models.TextField()
posted = models.DateTimeField(db_index=True, auto_now_add=True)
category = models.ForeignKey('Category')
def __unicode__(self):
return '%s' % self.title
#permalink
def get_absolute_url(self):
return ('view_blog_post', None, { 'slug': self.slug })
def __str__(self):
return self.title
class Category(models.Model):
title = models.CharField(max_length=100, db_index=True)
slug = models.SlugField(max_length=100, db_index=True)
def __unicode__(self):
return '%s' % self.title
#permalink
def get_absolute_url(self):
return ('view_blog_category', None, { 'slug': self.slug })
def __str__(self):
return self.title
you should try this 'posts': Blog.objects.all() in views.py

Django NoReverMatch at /

I read the book 'Django By Example' and run the examples in chaper7.
But the results call "NoReverMatch at /"
NoReverseMatch at /
Reverse for 'product_detail' with arguments '(5, u'ironman')' and keyword arguments '{}' not found. 1 pattern(s) tried: ['(?P<id>[\\d+])/(?P<slug>[-\\w+])/$']
This is the models.py
class Category(models.Model):
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_list_by_category', args=[self.slug])
class Product(models.Model):
category = models.ForeignKey(Category, related_name='products')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-created',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_detail', args=[self.id, self.slug])
This is the urls.py
urlpatterns = [
url(r'^$', views.product_list, name='product_list'),
url(r'^(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list_by_category'),
url(r'^(?P<id>\d+)/(?P<slug>[-\w+])/$', views.product_detail, name='product_detail'),
]
This is the views.py
def product_list(request, category_slug=None):
category = None
categories = Category.objects.all()
products = Product.objects.filter(available=True)
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
products = products.filter(category=category)
return render(request, 'shop/product/list.html', {'category': category, 'categories': categories, 'products': products})
def product_detail(request, id, slug):
product = get_object_or_404(Product,
id=id,
slug=slug,
available=True)
return render(request, 'shop/product/detail.html', {'product': product})
And this is the 'list.html' template where the error occurs.
{% extends "shop/base.html" %}
{% load static %}
{% block title %}
{% if category %}{{ category.name }}{% else %}Products{% endif %}
{% endblock %}
{% block content %}
<div id="sidebar">
<h3>Categories</h3>
<ul>
<li {% if not category %} class="selected" {% endif %}>
All
</li>
{% for c in categories %}
<li {% if category.slug == c.slug %} class="selected" {% endif %}>
{{ c.name }}
</li>
{% endfor %}
</ul>
</div>
<div id="main" class="product-list">
<h1>{% if category %}{{ category.name }}{% else %}Products{% endif %} </h1>
{% for product in products %}
<div class="item">
<a href="{{ product.get_absolute_url }}">
<img src="{% if product.image %}{{ product.image.url }}{% else %}{% static 'img/no_image.png' %}{% endif %}">
</a>
{{ product.name }}<br>
${{ product.price }}
</div>
{% endfor %}
</div>
{% endblock %}
The error occurs at
<a href="{{ product.get_absolute_url }}">
-- line.
Why this error occurs??
It looks to me like you need to change your url pattern:
url(r'^(?P<id>\d+)/(?P<slug>[-\w+])/$', views.product_detail, name='product_detail')
perhaps to:
url(r'^(?P<id>\d+)/(?P<slug>[-\w]+)/$', views.product_detail, name='product_detail')
'+' does not function as a special character inside square brackets, so [-\w+] will only match a single character (alphanumeric or '-'), but you are passing multi-character strings like 'ironman'. [-\w]+ will match one or more characters.

Categories