What I have been trying is to click the post's author(the user that created the post) I want it to redirect me to that user's profile, for example in Instagram when you click the user that is on top of the post-it redirects you to their profile. Every time I do that instead of seeing the post's author profile I see the logged in user profile. I think there is something wrong in the views.py file or in the base.html.
views.py
def profile(request, pk=None):
if pk:
user = get_object_or_404(User, pk=pk)
else:
user = request.user
args = {'user': user}
return render(request, 'profile.html', args)
def home(request):
created_posts = Create.objects.all().order_by("-added_date")
return render(request, 'base.html', {"created_posts": created_posts})
def create(request):
if request.method == 'POST':
created_date = timezone.now()
header1 = request.POST['header']
content1 = request.POST['content']
user = request.user
created_obj = Create.objects.create(added_date=created_date, title=header1, content=content1, user=user)
created_obj.save()
print('create created')
return redirect('home')
else:
print('create not created')
return render(request, 'create.html')
models.py
class Create(models.Model):
added_date = models.DateTimeField()
title = models.CharField(max_length=200)
content = models.CharField(max_length=200)
user = models.ForeignKey(User, related_name='user', on_delete=models.CASCADE, default=1)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
urls.py
urlpatterns = [
path('', views.home, name='home'),
path('profile', views.profile, name='profile'),
path('profile/<int:pk>/', views.profile, name='profile_pk'),
path('create', views.create, name='create'),
]
profile.html (shows user's profile)
{% extends 'home.html' %}
{% block body%}
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ user.username }}</h2>
<p class="text-secondary">{{ user.email }}</p>
</div>
</div>
</div>
{% endblock %}
base.html (shows all user's post with the user's username)
{% extends 'home.html' %}
{% block body %}
<ul action="{% url 'create' %}" class="container-sm list-group" style="margin-top: 200px;">
{% for created_post in created_posts %}
<li class="list-group-item">{{ created_post.title }}
{{ created_post.user }}
<p>{{ created_post.content }}</p>
<div class="float-right">
<form action="delete_create/{{ created_post.id }}/" action="post">
<button type="submit" class="btn btn-outline-danger btn-sm">Delete</button>
</form>
</div>
<div class="float-right">
Edit
</div>
</li>
{% endfor %}
</ul>
{% endblock %}
home.html (navbar that shows the loged in user)
<body>
<nav class="navbar navbar-expand-md fixed-top navbar-dark" style="background-color: rgba(0, 0, 0, 0.712);">
<div class="container">
<a class="navbar-brand" href="/">
<img src="static/style/images/logowebdev-png.png" alt="logo" style="width: 60px; height: auto;">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample07" aria-controls="navbarsExample07" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarsExample07">
<ul class="navbar-nav mr-auto mt-2 mt-lg-0">
<li class="nav-item">
<a class="nav-link" style="margin-left: 30px;" href="/">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" style="margin-left: 30px;" href="/profile">profile</a>
</li>
<li class="nav-item">
<a class="nav-link" style="margin-left: 30px;" href="#">Pricing</a>
</li>
</ul>
<ul class="navbar-nav ml-auto">
{% if user.is_authenticated %}
<div class="float-right">
<li class="nav-item active">
<a class="nav-link" href="#">New post</a>
</li>
</div>
<div class="float-right">
<li class="nav-item active">
<a class="nav-link" href="">{{ user.username }}</a>
</li>
</div>
<div class="float-right">
<li class="nav-item">
<a class="nav-link" href="/logout">Logout</a>
</li>
</div>
{% else %}
<div class="float-right">
<li class="nav-item">
<a class="nav-link" href="/login">Login</a>
</li>
</div>
<div class="float-right">
<li class="nav-item">
<a class="nav-link" href="/register">Register</a>
</li>
</div>
{% endif %}
</ul>
</div>
</div>
</nav>
{% block body %}
{% endblock %}
</body>
In your base.html file change
{{ created_post.user }}
with
{{ created_post.user }}
Because, you must pass id of post owner to your view. When you use only user, django detect authenticated user object.
Related
views.py
from django.shortcuts import render
from ecommerceapp.models import Product
from django.db.models import Q
def searchResult(request):
products=None
query=None
if 'q' in request.GET:
query = request.GET.get('q')
products=Product.objects.all().filter(Q(name__contains=query) | Q(desc__contains=query))
return render(request,'search.html',{'query':query,'products':products})
In views.py I have imported a model named 'Product' of another application.
search.html
{% extends 'base.html' %}
{% load static %}
{% block metadescription %}
Welcome to FASHION STORE-Your Beauty
{% endblock %}
{% block title %}
Search-FASHION STORE
{% endblock %}
{% block content %}
<div>
<p class="text-center my_search_text">You have searched for :<b>"{{query}}"</b></p>
</div>
<div class="container">
<div class="row mx_auto">
{% for product in products %}
<div class="my_bottom_margin col-9 col-sm-12 col-md-6 col-lg-4" >
<div class="card text-center" style="min-width:18rem;">
<img class="card-img-top my_image" src="{{product.image.url}}" alt="{{product.name}}" style="height:400px; width:100%;">
<div class="card_body">
<h4>{{product.name}}</h4>
<p>₹{{product.price}}</p>
</div>
</div>
</div>
{% empty %}
<div class="row mx_auto">
<p class="text-center my_search_text">0 results found.</p>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
navbar.html
<nav class="navbar navbar-expand-lg bg-light">
<div class="container-fluid">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item dropdown {% if 'ecommerceapp' in request.path %} active {% endif %} ">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Shop
</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="{% url 'ecommerceapp:allProductCategory' %}">All Products</a></li>
{% for cat in links %}
<li><a class="dropdown-item" href="{{cat.get_url}}">{{cat.name}}</a></li>
{% endfor %}
</ul>
</li>
<li class="nav-item">
<a class="nav-link disabled" href=""><i class="fa fa-shopping-cart"></i></a>
</li>
</ul>
<form class="d-flex" action="{% url 'search_app:searchResult' %}" method="get">
{% csrf_token %}
<input class="form-control me-2" type="search" placeholder="Search" name="q" aria-label="Search">
<button class="btn btn-outline-success" type="submit"><i class="fa fa-search"></i></button>
</form>
</div>
</div>
</nav>
When I'm searching using search bar, not getting the correct results. When giving the word completely, correct results are getting.
Example: When I type x in the search bar, it give me the results 'shirt' instead of giving '0 results found'.
Example: When I type x in the search bar, it give me the results 'shirt' instead of giving '0 results found'.
The __contains is used to check whether the field contains given word or not, it is case-sensitive. And using | in Q objects means it is optional and works as OR condition, so maybe it is possible when you type x, the name field doesn't contains x but the field desc contain x that's why you are getting the shirt as instance or else you can simply put the query to Product.objects.filter(Q(name__contains=query)) and .all() only creates the copy of the Queryset so it doesn't require here.
I was successful at getting the form to appear on the modal which was an issue I had earlier, now I'm struggling to make this work. Any way to work my way around this?? Also I wanna check if method == 'POST' before checking if the form is valid but can't seem to find a solution..
views:
class ProfileDetailView(LoginRequiredMixin, DetailView):
model = Profile
template_name = 'network/profile.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
user = User.objects.get(username__iexact=self.request.user)
profile = Profile.objects.get(user=user)
form = ProfileModelForm(instance=profile)
confirm = False
rel_r = Relationship.objects.filter(sender=profile)
rel_s = Relationship.objects.filter(receiver=profile)
rel_receiver = []
rel_sender = []
for item in rel_r:
rel_receiver.append(item.receiver.user)
for item in rel_s:
rel_sender.append(item.sender.user)
if form.is_valid():
form.save()
confirm = True
context["rel_receiver"] = rel_receiver
context["rel_sender"] = rel_sender
context["posts"] = self.get_object().get_all_authors_posts()
context["len_posts"] = True if len(self.get_object().get_all_authors_posts()) > 0 else False
context["form"] = form
context["confirm"] = confirm
context["profile"] = profile
return context
Form:
class ProfileModelForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('first_name', 'last_name', 'bio', 'avatar')
Model:
class Profile(models.Model):
first_name = models.CharField(max_length=64, blank=True)
last_name = models.CharField(max_length=64, blank=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
country = models.CharField(max_length=64, blank=True)
avatar = models.ImageField(upload_to='avatars', default='avatar.png')
background = models.ImageField(upload_to='backgrounds', default='background.png')
following = models.ManyToManyField(User, related_name='following', blank=True)
bio = models.TextField(default="No Bio..")
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
slug = models.SlugField(unique=True, blank=True)
objects = ProfileManager()
def __str__(self):
return f"{self.user.username}"
def get_absolute_url(self):
return reverse("profile-view", kwargs={"slug": self.slug})
HTML:
{% extends "network/layout.html" %}
{% load static %}
{% load crispy_forms_tags %}
{% block title %}
My Profile
{% endblock title %}
{% block body %}
<!--Modal-->
<div class="modal fade" id="profileModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Update Your Profile</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<img width="100px" src="{{profile.avatar.url}}">
<form action="", method="POST", enctype="multipart/form-data" class="form">
{% csrf_token %}
{{form}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</div>
</div>
</div>
</div>
<div>
{% if confirm %}
<div class="alert alert-info" role="alert">Your profile has been updated!</div>
{% endif %}
</div>
<div class="row py-5 px-4">
<div class="col-md-5 mx-auto">
<!-- Profile widget -->
<div class="bg-white shadow rounded overflow-hidden">
<div class="px-4 pt-0 pb-4 cover">
<div class="media align-items-end profile-head">
<div class="profile mr-3"><img src="{{object.avatar.url}}" width="130" class="rounded mb-2 img-thumbnail"></div>
<div class="media-body mb-5 text-white">
<h4 class="mt-0 mb-3">{{profile.first_name}} {{profile.last_name}}</h4>
<p style="color: black;" class="small mb-4"> <i class="fas fa-map-marker-alt mr-2"></i>{{profile.country}}</p>
</div>
</div>
</div>
<div class="bg-light p-5 d-flex justify-content-end text-center">
<ul class="list-inline mb-0">
<li class="list-inline-item">
<h5 class="font-weight-bold mb-0 d-block">{{object.get_posts_num}}</h5><small class="text-muted"> <i class="fas fa-image mr-1"></i>Posts</small>
</li>
<li class="list-inline-item">
<h5 class="font-weight-bold mb-0 d-block">{{object.get_followers_num}}</h5><small class="text-muted"> <i class="fas fa-user mr-1"></i>Followers</small>
</li>
<li class="list-inline-item">
<h5 class="font-weight-bold mb-0 d-block">340</h5><small class="text-muted"> <i class="fas fa-user mr-1"></i>Following</small>
</li>
<li class="list-inline-item">
<h5 class="font-weight-bold mb-0 d-block">{{object.get_liked}}</h5><small class="text-muted"> <i class="fas fa-user mr-1"></i>Likes</small>
</li>
</ul>
</div>
<div class="ml-2">
{% if object.user and object.user not in rel_receiver and object.user not in rel_sender %}
<form action="{% url 'send-invite' %}" method="POST">
{% csrf_token %}
<input type="hidden" name="profile_pk" value={{object.pk}}>
<button type="submit" class=" btn btn-sm btn-success w-btn"><i class="bi-plus-lg"></i> Follow</button>
</form>
{% endif %}
{% if object.user in rel_receiver and request.user not in object.following.all %}
<button class="btn btn-sm disabled "><i class="bi-three-dots"></i> Waiting aprroval</button>
{% endif %}
{% if request.user in object.following.all %}
<form action="{% url 'remove-friend' %}" method="POST">
{% csrf_token %}
<input type="hidden" name="profile_pk" value={{object.pk}}>
<button type="submit" class=" btn btn-sm btn-dark w-btn"><i class="bi-dash-lg"></i> Unfollow</button>
</form>
{% endif %}
</div>
<div class="px-4 py-3">
<h5 class="mb-0">About</h5>
<button class="btn btn-sm btn-secondary float-right" id="modal-btn" data-toggle="modal" data-target="#profileModal">Edit Profile</button>
<div class="p-4 rounded shadow-sm bg-light">
<p class="font-italic mb-0">{{profile.bio}}</p>
</div>
</div>
<div class="py-4 px-4">
<div class="d-flex align-items-center justify-content-between mb-3">
<h5 class="mb-0">Recent posts</h5>Show all
</div>
{% if len_posts %}
<div class="row">
{% for post in posts %}
<div class="col-lg-6 mb-2 pr-lg-1 fluid">
{% if post.picture %}
<img class="card-img-profile" src="{{post.picture.url}}">
{% endif %}
{{post.content}}
</div>
{% endfor %}
{% else %}
<h1>This user didn't post anything yet..</h1>
{% endif %}
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
Not sure if you have tried this:
In your view you should write a function called post.
def post(self, request):
if request.method == 'POST':
form = self.form(request.POST)
if form.is_valid():
*whatever you need to do after you've validated the from*
So I'm getting this error when I visit the page, I'm trying to use paginator and I don't know where i'm wrong, index function handles the page I'm talking about
views.py
def index(request):
listings = Listing.objects.all()
paginator = Paginator(listings, 3)
page = request.GET.get('page')
paged_listings = paginator.get_page(page)
params = {'listings':paged_listings}
return render(request, 'listings/listings.html', params)
def listing(request, listing_id):
return render(request, 'listings/listing.html')
def search(request):
return render(request, 'listings/search.html')
listings.html
{% extends 'base.html' %}
{% block content %}
{% load humanize %}
<!-- Breadcrumb -->
<section id="bc" class="mt-3">
<div class="container">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="{% url 'index' %}">
<i class="fas fa-home"></i> Home</a>
</li>
<li class="breadcrumb-item active"> Browse Listings</li>
</ol>
</nav>
</div>
</section>
<!-- Listings -->
<section id="listings" class="py-4">
<div class="container">
<div class="row">
{% if listings %}
{% for listing in listings %}
<div class="col-md-6 col-lg-4 mb-4">
<div class="card listing-preview">
<img class="card-img-top" src="{{ listing.photo_main.url }}" alt="">
<div class="card-img-overlay">
<h2>
<span class="badge badge-secondary text-white">${{ listing.price | intcomma}}</span>
</h2>
</div>
<div class="card-body">
<div class="listing-heading text-center">
<h4 class="text-primary">{{ listing.title }}</h4>
<p>
<i class="fas fa-map-marker text-secondary"></i>{{ listing.city }} {{ listing.state }}, {{ listing.zipcode }}</p>
</div>
<hr>
<div class="row py-2 text-secondary">
<div class="col-6">
<i class="fas fa-th-large"></i>Sqfit: {{ listing.sqft }}</div>
<div class="col-6">
<i class="fas fa-car"></i>Garage: {{ listing.garage }}</div>
</div>
<div class="row py-2 text-secondary">
<div class="col-6">
<i class="fas fa-bed"></i>Bedrooms: {{ listing.bedrooms }}</div>
<div class="col-6">
<i class="fas fa-bath"></i>Bathrooms: {{ listing.bathrooms }}</div>
</div>
<hr>
<div class="row py-2 text-secondary">
<div class="col-12">
<i class="fas fa-user"></i>{{ listing.realtor.name }}</div>
</div>
<div class="row text-secondary pb-2">
<div class="col-6">
<i class="fas fa-clock"></i>{{ listing.list_date | timesince }}</div>
</div>
<hr>
More Info
</div>
</div>
</div>
{% endfor %}
{% else %}
<div class="col-md-12">
<p>No Listings Available</p>
</div>
{% endif %}
<!-- Listing 1 -->
</div>
<div class="row">
<div class="col-md-12">
{% if listings.has_other_pages %}
<ul class="pagination">
{% if listings.has_previous %}
<li class="page-item">
«
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link">«</a>
</li>
{% endif %}
</ul>
{% endif %}
{% for i in listings.paginator.page_rage %}
{% if listings.number == i %}
<li class="page-item active">
<a class="page-link">{{ i }}</a>
</li>
{% else %}
<li class="page-item">
{{i}}
</li>
{% endif %}
{% endfor %}
</div>
</div>
</div>
</section>
{% endblock %}
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name="listings"),
path('<int:listing_id>', views.listing, name="=listing"),
path('search', views.search, name="=search"),
]
There's a Typo in your urls.py
Try to use this :-
path('listing/<int:listing_id>/', views.listing, name='listing'),
Where was the typo ?
You were using this :-
path('<int:listing_id>', views.listing, name="=listing"),
----------------------------------------------^
I am new to Python and Django, and I have just created a website.
Basically I would like to have a page on the website that displays our company partners.
I have created an app 'partners' and in the model, I have 'website' as one of the fields.
On the partners html file, I have a button that users can click and this will take them to the partner's website in a new tab.
I tried to link the website in the following way:
{{ partner.website }}
However this ends up like:
www.mydomain.com/partners/www.partnerwebsite.com
I just want the partner website (www.partnerwebsite.com) to open in a new tab.
Any help appreciated. If there is already another post on this, please redirect me.
views.py
from django.shortcuts import render, redirect
from .models import Partner
def index(request):
partners = Partner.objects.order_by('-date_added').filter(is_published=True)
context = {
'partners': partners,
}
return render(request, 'partners/partners.html', context)
models.py
from django.db import models
from datetime import datetime
class Partner(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
website = models.CharField(max_length=100)
email = models.CharField(max_length=200)
contact_person = models.CharField(max_length=200)
phone = models.CharField(max_length=100)
mobile = models.CharField(max_length=100)
address = models.CharField(max_length=200)
photo_main = models.ImageField(upload_to='photos/partners/%Y/%m/%d/')
promo_code = models.CharField(max_length=20, blank=True)
is_published = models.BooleanField(default=True)
date_added = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.name
partners.html
{% extends 'base.html' %}
{% block title %} | Partners {% endblock %}
{% block content %}
<section id="showcase-inner" class="py-5 text-white">
<div class="container">
<div class="row text-center">
<div class="col-md-12">
<h1 class="display-4">Partners</h1>
</div>
</div>
</div>
</section>
<!-- Breadcrumb -->
<section id="bc" class="mt-3">
<div class="container">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="{% url 'index' %}">
<i class="fas fa-home"></i> Home</a>
</li>
<li class="breadcrumb-item active"> Partners</li>
</ol>
</nav>
</div>
</section>
<!-- Partners -->
<section id="partners" class="py-4">
<div class="container">
<div class="row">
{% if partners %}
{% for partner in partners %}
<!-- Partner 1 -->
<div class="col-md-6 col-lg-6 mb-4">
<div class="card listing-preview">
<img class="card-img-top-project" src="{{ partner.photo_main.url }}" alt="">
<div class="card-body">
<div class="listing-heading text-center">
<h4 class="text-primary">{{ partner.name | title }}</h4>
<p><i class="fas fa-map-marker text-secondary"></i> {{ partner.address }}</p>
</div>
<hr>
<div class="row py-2 text-secondary">
<div class="col-12 text-center">
{{ partner.description }}
</div>
</div>
{% if partner.promo_code %}
<hr>
<div class="row py-2 text">
<div class="col-12 text-center">
Use the following code to obtain 10% discount: {{ partner.promo_code }}
</div>
</div>
{% endif %}
<div class="container">
<hr>
<button class="btn btn-secondary btn-block">Visit Website</button>
</div>
</div>
</div>
</div>
{% endfor %}
{% else %}
<div class="container">
<p><h5 class="text-center">No Partners Available</h5></p>
</div>
{% endif %}
</div>
</div>
</section>
{% endblock %}
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.index, name='partners'),
]
I was able to deduce the below solution from your views file. Add the below code in your template "partners.html"
{% for value in partners %}
<button>my button </button>
{% endfor%}
I am a newbie in django learning django with a online course by creating a realestate project.In this project I am having listings app which shows some of the listings in the web page from the database But I am getting an error of Reverse for 'listing' with arguments '('',)' not found. 1 pattern(s) tried: ['listings/listings/$']
My listings urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='listings'),
url(r'^listings/<int:listing_id>$', views.listing, name='listing'),
url('search', views.search,name='search')
]
My listings views.py
from django.shortcuts import get_object_or_404, render
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from .models import Listing
def index(request):
listings = Listing.objects.order_by('-list_date').filter(is_published=True)
paginator = Paginator(listings, 6)
page = request.GET.get('page')
paged_listings = paginator.get_page(page)
context = {
'listings': paged_listings
}
return render(request, 'listings/listings.html', context)
def listing(request, listing_id):
listing = get_object_or_404(Listing, pk=listing_id)
context = {
'listing': listing
}
return render(request, 'listings/listing.html', context)
def search(request):
queryset_list = Listing.objects.order_by('-list_date')
# Keywords
if 'keywords' in request.GET:
keywords = request.GET['keywords']
if keywords:
queryset_list = queryset_list.filter(description__icontains=keywords)
# City
if 'city' in request.GET:
city = request.GET['city']
if city:
queryset_list = queryset_list.filter(city__iexact=city)
# State
if 'state' in request.GET:
state = request.GET['state']
if state:
queryset_list = queryset_list.filter(state__iexact=state)
# Bedrooms
if 'bedrooms' in request.GET:
bedrooms = request.GET['bedrooms']
if bedrooms:
queryset_list = queryset_list.filter(bedrooms__lte=bedrooms)
# Price
if 'price' in request.GET:
price = request.GET['price']
if price:
queryset_list = queryset_list.filter(price__lte=price)
context = {
'state_choices': state_choices,
'bedroom_choices': bedroom_choices,
'price_choices': price_choices,
'listings': queryset_list,
'values': request.GET
}
return render(request, 'listings/search.html', context)
My listings template
{% extends 'pages/base.html' %}
{% load humanize %}
{% block title %} | Browse Property Listings {% endblock %}
{% block content %}
<section id="showcase-inner" class="py-5 text-white">
<div class="container">
<div class="row text-center">
<div class="col-md-12">
<h1 class="display-4">Browse Our Properties</h1>
<p class="lead">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Sunt, pariatur!</p>
</div>
</div>
</div>
</section>
<!-- Breadcrumb -->
<section id="bc" class="mt-3">
<div class="container">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="{% url 'index' %}">
<i class="fas fa-home"></i> Home</a>
</li>
<li class="breadcrumb-item active"> Browse Listings</li>
</ol>
</nav>
</div>
</section>
<!-- Listings -->
<section id="listings" class="py-4">
<div class="container">
<div class="row">
{% if listings %}
{% for listing in listings %}
<div class="col-md-6 col-lg-4 mb-4">
<div class="card listing-preview">
<img class="card-img-top" src="{{ listing.photo_main.url }}" alt="">
<div class="card-img-overlay">
<h2>
<span class="badge badge-secondary text-white">${{ listing.price | intcomma }}</span>
</h2>
</div>
<div class="card-body">
<div class="listing-heading text-center">
<h4 class="text-primary">{{ listing.title }}</h4>
<p>
<i class="fas fa-map-marker text-secondary"></i> {{ listing.city }} {{ listing.state }}, {{ listing.zipcode }}</p>
</div>
<hr>
<div class="row py-2 text-secondary">
<div class="col-6">
<i class="fas fa-th-large"></i> Sqft: {{ listing.sqft }}</div>
<div class="col-6">
<i class="fas fa-car"></i> Garage: {{ listing.garage }}</div>
</div>
<div class="row py-2 text-secondary">
<div class="col-6">
<i class="fas fa-bed"></i> Bedrooms: {{ listing.bedrooms }}</div>
<div class="col-6">
<i class="fas fa-bath"></i> Bathrooms: {{ listing.bathrooms }}</div>
</div>
<hr>
<div class="row py-2 text-secondary">
<div class="col-12">
<i class="fas fa-user"></i> {{ listing.realtor }}</div>
</div>
<div class="row text-secondary pb-2">
<div class="col-6">
<i class="fas fa-clock"></i> {{ listing.list_date | timesince }}</div>
</div>
<hr>
More Info
</div>
</div>
</div>
{% endfor %}
{% else %}
<div class="col-md-12">
<p>No Listings Available</p>
</div>
{% endif %}
</div>
<div class="row">
<div class="col-md-12">
{% if listings.has_other_pages %}
<ul class="pagination">
{% if listings.has_previous %}
<li class="page-item">
«
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link">«</a>
</li>
{% endif %}
{% for i in listings.paginator.page_range %}
{% if listings.number == i %}
<li class="page-item active">
<a class="page-link">{{i}}</a>
</li>
{% else %}
<li class="page-item">
{{i}}
</li>
{% endif %}
{% endfor %}
{% if listings.has_next %}
<li class="page-item">
»
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link">»</a>
</li>
{% endif %}
</ul>
{% endif %}
</div>
</div>
</div>
</section>
{% endblock %}
You are using django 3, and url patterns from django 1. Try this:
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='listings'),
path('listings/<int:listing_id>', views.listing, name='listing'),
path('search', views.search, name='search')
]
in template
More Info
If you are using a Django version 2+, you could use path instead:
path('listings/<int:listing_id>/', views.listing, name='listing'),
If your using lower django version than 2
url(r'^listings/(?P<listing_id>[0-9]+)/$', views.listing, name='listing'),
Now in the template
<a href="{% url 'listing' listing.pk %}">