Django error: NoReverseMatch at : I get this error - python

I have the following conceptual error which I am not undertstanding:
Please have a look at the thrown error:
NoReverseMatch at /watchlist
Reverse for 'auction' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<auction_id>[0-9]+)$']
Request Method: GET
Request URL: http://127.0.0.1:8000/watchlist
This is my urls.py file:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("<int:auction_id>", views.auction, name="auction"),
path("new", views.newItem, name="newItem"),
path("watchlist", views.watchlist, name="watchlist"),
path("addwatchList/<int:auction_id>", views.add_watchlist, name="add_watchlist"),
path("remwatchList/<int:auction_id>", views.rem_watchlist, name="rem_watchlist"),
]
And the views.py file fragment where the errors occurs is this:
#login_required
def watchlist(request):
u = User.objects.get(username=request.user)
return render(request, "auctions/watchlist.html", {
"watcher": u.watchingAuction.all()
})
Assigning the "watcher" variable makes the application brake and show the error message.
Can you please help me out? Where is the conceptual mistake?
Thnkass
This is my Watchlist.html file:
{% extends "auctions/layout.html" %}
{% block body %}
<h2 style="text-align: center;">My Watchlist!</h2>
<hr>
{% if watcher%}
<div class="row">
{% for item in watcher %}
<div class="card" style="width: 18rem;">
<img src="{{item.watchingAuction.url}}" class="card-img-top" alt="..." style="max-height: 200px; min-height: 200px; max-width: 180px; min-width: 180px;">
<div class="card-body">
<h5 class="card-title">{{item.watchingAuction.name}}</h5>
<h6 class="card-title">Price: ${{item.watchingAuction.startBid}}</h6>
<h6 class="card-title">{{item.watchingAuction.owner}}</h6>
<p class="card-text">{{item.watchingAuction.description}}</p>
To Auction
</div>
</div>
{% endfor %}
{% else %}
<h3 style="text-align: center; color:darkslateblue;">No auctions watched so far</h3>
{% endif %}
</div>
{% endblock %}
This is my models.py file:
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
class Auction(models.Model):
NOCAT = 'NO'
SURF = 'SU'
KITESURF = 'KI'
WINDSURF = 'WI'
SKI = 'SK'
BASE = 'BA'
CATEGORY_CHOICES = [
(NOCAT, 'Nocat'),
(SURF, 'Surf'),
(KITESURF, 'Kitesurf'),
(WINDSURF, 'Windsurf'),
(SKI, 'Ski'),
(BASE, 'Base'),
]
owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="auctionOwner")
name = models.CharField(max_length=64)
description = models.TextField(max_length=200)
startBid = models.FloatField()
currentBid = models.FloatField(blank=True, null=True)
url = models.URLField(blank=True)
watching = models.ManyToManyField(User, blank=True, related_name="watchingAuction")
category = models.CharField(
blank=True,
max_length=2,
choices=CATEGORY_CHOICES,
default=SURF )
def __str__(self):
return f"{self.name} {self.startBid} {self.category}"
def snippet(self):
return self.description[:25] + "..."
class Bids(models.Model):
item = models.ForeignKey(Auction, on_delete=models.CASCADE, related_name="itemBid")
bidder = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bidMan")
bid = models.FloatField()
def __str__(self):
return f"{self.bidder} {self.bid}"
class Comments(models.Model):
comment = models.TextField(max_length=300)
commenter = models.ForeignKey(User, on_delete=models.CASCADE, related_name="userComment")
item = models.ManyToManyField(Auction,blank=True, related_name="speech")
def __str__(self):
return f"{self.commenter} says: {self.comment}"

I found the bug, I was accessing the wrong attributes of each element in the for loop. Now it is solved

Related

pk argument on Django blog

I'm working on a blog and I was following instructions but now I don't understand why I have problem with pk.
This is my views.py
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import Category, Post
def post_list(request):
posts = Post.objects.filter(created_at__lte=timezone.now()).order_by('created_at')
latest_posts = Post.objects.filter(created_at__lte=timezone.now()).order_by('created_at')[:9]
context = {'posts': posts, 'latest_posts': latest_posts}
return render(request, 'home.html', context)
def post_detail(request, post, pk):
latest_posts = Post.objects.filter(created_at__lte=timezone.now()).order_by('created_at')[:9]
post = get_object_or_404(Post, pk=pk)
context = {'post': post, 'latest_posts': latest_posts}
return render(request, 'post_detail.html', context)
This is blog/urls.py
urlpatterns = [
path('', views.post_list, name='home'),
path('<slug:post>/', views.post_detail, name='post_detail'),
]
This is models.py
class Post(models.Model):
created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at")
updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at")
is_published = models.BooleanField(default=False, verbose_name="Is published?")
published_at = models.DateTimeField(null=True, blank=True, editable=False, verbose_name="Published at")
title = models.CharField(max_length=200, verbose_name="Title")
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey('auth.User', verbose_name="Author", on_delete=models.CASCADE)
category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE)
body = RichTextField(blank=True, null=True)
image = StdImageField(upload_to='featured_image/%Y/%m/%d/', variations={'standard':(1170,820),'banner':(1170,530),'thumbnail':(500,500)})
status = models.IntegerField(choices=STATUS, default=0)
def get_absolute_url(self):
return reverse('post_detail', args=[self.slug])
class Meta:
verbose_name = "Post"
verbose_name_plural = "Posts"
ordering = ['-created_at']
def publish(self):
self.is_published = True
self.published_at = timezone.now()
self.save()
def __str__(self):
return self.title
Also, I'm adding a list of post, it might be connected with get_absolute_url
{% extends "base.html" %}
{% load static %}
{% block content %}
<!-- Main Wrap Start -->
<main class="position-relative">
<div class="post-carausel-1-items mb-50">
{% for post in latest_posts %}
<div class="col">
<div class="slider-single bg-white p-10 border-radius-15">
<div class="img-hover-scale border-radius-10">
<!--<span class="top-right-icon bg-dark"><i class="mdi mdi-flash-on"></i></span>-->
<a href="{{ post.get_absolute_url }}">
<img class="border-radius-10" src="{{ post.image.standard.url }}" alt="post-slider">
</a>
</div>
<h6 class="post-title pr-5 pl-5 mb-10 mt-15 text-limit-2-row">
{{ post.title }}
</h6>
<div class="entry-meta meta-1 font-x-small color-grey float-left text-uppercase pl-5 pb-15">
<span class="post-by">By {{ post.author }}</span>
<span class="post-on">{{ post.created_at}}</span>
</div>
</div>
</div>
{% endfor %}
</div>
</main>
{% endblock content%}
I have an error...
post_detail() missing 1 required positional argument: 'pk'
Everything was working until I was started working on post detail. Any ideas why this is happening?
You seem to be confused with what the primary key for your model is. The primary key is the auto-generated id (pk) but according to your urls.py you want to use slug for fetching records.
First, change your path to:
path('<slug:slug>/', views.post_detail, name='post_detail'),
then your view signature to:
def post_detail(request, slug):
and finally, fetch your record using:
post = get_object_or_404(Post, slug=slug)

Accessing a parent model attribute within Django template

I have an app that has a list of projects, and each project has a number of posts, and when you click on a project, it shows all of the posts in that project, but I can't figure out how to make it display what project the user is currently on, sample of it not working It should say "Posts for project 1" for example. Here is the relevant code of what I have so far.
<h1 class="mb-3">Posts for {{ post.project.title }}</h1>
{% for post in posts %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
</div>
<h2><a class="article-title">{{ post.title }}</a></h2>
<p class="article-content">{{ post.description }}</p>
</div>
</article>
{% endfor %}
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(default='')
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('project-detail', kwargs = {'pk': self.pk})
class Post(models.Model):
def get_default_action_status():
return Project.objects.get(title="bruh")
project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='posts', default=get_sentinel_exam_id)
title = models.CharField(max_length=100)
description = models.TextField(default='')
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
LOW = '!'
MED = '!!'
HIGH = '!!!'
YEAR_IN_SCHOOL_CHOICES = [
(LOW, '!'),
(MED, '!!'),
(HIGH, '!!!'),
]
severity = models.CharField(
max_length=3,
choices=YEAR_IN_SCHOOL_CHOICES,
default=LOW,
)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs = {'pk': self.pk})
urlpatterns = [
path('', ProjectListView.as_view(), name='blog-home'),
path('user/<str:username>', UserProjectListView.as_view(), name='user-projects'),
path('project/<str:title>', ProjectPostListView.as_view(), name='project-posts'),
path('post/<int:pk>/', ProjectDetailView.as_view(), name='project-detail'),
path('post/new/', ProjectCreateView.as_view(), name='project-create'),
path('post/<int:pk>/update/', ProjectUpdateView.as_view(), name='project-update'),
path('post/<int:pk>/delete/', ProjectDeleteView.as_view(), name='project-delete'),
path('about/', views.about, name='blog-about'),
]
class ProjectPostListView(ListView):
model = Post
template_name = 'blog/project_posts.html'
context_object_name = 'posts'
paginate_by = 10
def get_queryset(self):
project = get_object_or_404(Project, title=self.kwargs.get('title'))
return Post.objects.filter(project=project).order_by('-date_posted')
Apologies if some of that code wasn't needed, I am new to Django.
I figured it out by making the model of "ProjectPostListView" into a Project, and then changing that to a DetailView so I could just use all of the post objects associated with that project.

Get Absolute Url keeps directing to one particular id

Good day, I have a Django project where I want to display an order list and detail. All seems to work perfectly but the link only links to one particular id ( for instance id 66). I have tried deleting the particular order id from the admin panel, thinking maybe the URL would just reset, but I get the URL id incremented, now it's no longer id 66 but 67. Pls how can I fix this? here are my codes:
models.py
class Order(models.Model):
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
address = models.CharField(max_length=250)
phone_number = models.CharField(max_length=20)
city = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
paid = models.BooleanField(default=False)
braintree_id = models.CharField(max_length=150, blank=True)
coupon = models.ForeignKey(Coupon, related_name='orders', null=True, blank=True, on_delete=models.SET_NULL)
discount = models.IntegerField(default=0, validators=[
MinValueValidator(0),
MaxValueValidator(100)
])
class Meta:
ordering = ('-created',)
def __str__(self):
return self.first_name
def get_absolute_url(self):
return reverse('orders:orderdetail', args=[self.id])
views.py
def order_list(request):
orders = Order.objects.all()
current_user = request.user
success = Order.objects.filter(user=current_user.id).filter(paid=True)
fail = Order.objects.filter(user=current_user.id).filter(paid=False)
return render(request, 'orders/order/order_list.html', {
'success': success,
'fail': fail,
'current_user': current_user,
'orders':orders,
})
def order_detail(request, order_id):
order = get_object_or_404(Order, id=order_id)
return render(request, 'orders/order/order_detail.html', {'order': order})
urls.py
from django.urls import path
from . import views
app_name = 'orders'
urlpatterns = [
path('create/', views.order_create, name='order_create'),
path('admin/order/<int:order_id>/', views.admin_order_detail, name='admin_order_detail'),
path('admin/order/<int:order_id>/pdf/', views.admin_order_pdf, name='admin_order_pdf'),
path('addtocart/<int:id>', views.addtocart, name='addtocart'),
path('myorder/', views.order_list, name='orderlist'),
path('myorder/detail/<int:order_id>/', views.order_detail, name='orderdetail'),
]
html
{% for order in orders %}
<a href="{{ order.get_absolute_url }}" style="position: absolute; top: 5px; right: 5px;">
View Details
</a>
{% endfor %}
full html
<div class="col-md-9">
{% for od in success %}
<div class="card mb-3" style="max-width: 540px;">
<div class="row no-gutters">
<div class="col-md-3">
<img alt="product img" class="card-img" src="...">
</div>
<div class="col-md-9">
<div class="card-body" style="position: relative;">
<h5 class="card-title">Product {{ od.id }}</h5>
{% for order in orders %}
<a href="{{ order.get_absolute_url }}" style="position: absolute; top: 5px; right: 5px;">
View Details
</a>
{% endfor %}
<p class="card-text">
<mark style="color: whitesmoke; background-color: brown;border-radius: 3px;font-weight: bold;">{{transaction}}</mark>
</p>
<p class="card-text"><small class="text-muted">Delivered at
{{od.reference_id}}</small></p>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
The URL I get is like this /orders/myorder/detail/66/
I'm gonna add pictures to make it less abstract
Thanks.
Just like #EricMartin said, it was the context of the order
I realized I had {% for od in success %} and {% for order in orders %}
I guess they're not on good terms with each other and since orders is in success, I removed the {% for order in orders %} loop and all seems peaceful again :)

Cannot resolve NoReverseMatch at / error in Django

I am trying to make an auction website (for a project). And we need to have an option to add each product to the "watchlist". However, I keep getting error when clicking on "watchlist" button. This is in Python using Django.
This is the exact error I'm getting:
NoReverseMatch at /viewlisting/3/addwatchlist
Reverse for 'addwatchlist' with arguments '('',)' not found. 1 pattern(s) tried: ['viewlisting/(?P<listing_id>[0-9]+)/addwatchlist$']
Here is a summary of my code:
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("create_listing", views.create_listing, name="create_listing"),
path("viewlisting/<int:listing_id>", views.viewlisting, name="viewlisting"),
path("viewlisting/<int:listing_id>/addwatchlist", views.addwatchlist, name="addwatchlist")
]
views.py:
def viewlisting(request,listing_id):
productname= listings.objects.get(id=listing_id)
name= productname.name
description = productname.description
image = productname.image
price= productname.price
seller = productname.seller
category = productname.category
date = productname.date
productid= productname.id
return render(request, "auctions/viewlisting.html",{
"name":name,
"description":description,
"image":image,
"price":price,
"seller":seller,
"category":category,
"date":date,
"id":productid
})
def addwatchlist(request,listing_id):
if request.method == "POST":
item_exists= watchlist.objects.filter(
id = listing_id, user= request.user.username
)
if item_exists:
show_watchlist = watchlist.objects.all()
exist_alert= "This item already exists in your watchlist!"
return render(request,"auctions/viewlisting.html",{
"alert":exist_alert,
"show_watchlist":show_watchlist
})
else:
new_item = watchlist()
new_item.user = request.user.username
new_item.listing = listings.objects.get(id=listing_id).name
new_item.save()
success_alert = "This item was added to your watchlist!"
show_watchlist = watchlist.objects.all()
return render(request,"auctions/viewlisting.html",{
"alert": success_alert,
"show_watchlist":show_watchlist,
})
else:
return render(request,"auctions/viewlisting.html")
And this is my viewlisting html page which renders different product detials and allows the user to add the product to their watchlist.
viewlisting.html:
{% extends "auctions/layout.html" %}
{% block body%}
<div class="container-fluid">
<div class="row">
<div class="col-md-4"><img src={{image}} style="max-width: 350px;"></div>
<div class="col-md-4"><strong>{{ name }}</strong><br> {{description}}
</div>
<div class="col-md-4">
<strong>Current Price:</strong> <sup>CAD$</sup>{{price}}
<br>
<strong>Category:</strong> {{ category }}
<br>
<br>
<form action="{% url 'addwatchlist' id %}" method="POST">
{% csrf_token %}
<button style="color:ghostwhite" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Add to Watchlist
</button>
</form>
</div>
</div>
<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">{{alert}}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h6>Your Watchlist:</h6>
{% for i in show_watchlist %}
<li>{{i.listing}</li>
{% endfor %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
And this is models.py:
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
def __str__ (self):
return f"username:{self.username}, email:{self.email}, password:{self.password}"
class listings(models.Model):
name = models.CharField(max_length=70, null= True, unique=True)
seller = models.CharField(max_length=100)
price = models.IntegerField(null= True)
category = models.CharField(max_length=100, null=True)
date = models.DateTimeField(auto_now=True)
description= models.CharField(max_length=500)
image= models.URLField()
def __str__ (self):
return f"{self.name} by {self.seller}: {self.price}, {self.category}, {self.date}, {self.description}, {self.date}, {self.image} "
class bids(models.Model):
bidder = models.ForeignKey(User, on_delete= models.CASCADE, related_name="bidder", null=True)
bid_price = models.IntegerField(null= True)
product= models.ForeignKey(listings, on_delete= models.CASCADE, to_field= "name", null=True)
bid_date = models.DateTimeField(auto_now=True, null=True)
def __str__(self):
return f"{self.bidder} bid {self.bid_price} on {self.product}: posted on {self.bid_date}"
class comments(models.Model):
commenter = models.ForeignKey(User, on_delete= models.CASCADE, related_name="commenter", null=True)
content = models.CharField(max_length=500, null=True)
post_date = models.DateTimeField(auto_now=True)
listing = models.ForeignKey(listings, on_delete= models.CASCADE, to_field= "name",null=True)
def __str__(self):
return f"{self.commenter} commented {self.content} on listing: {self.listing} ({self.post_date})"
class watchlist(models.Model):
user=models.CharField(max_length=500)
listing = models.CharField(max_length=500)
def __str(self):
return f"User: {self.user}, Product: {self.listing}"
I would really appreciate any help or hints.
Also, let me know if you need more explanations.
This is because you are passing id in form url and listing_id in urls.py
change <form action="{% url 'addwatchlist' id %}" method="POST"> to <form action="{% url 'addwatchlist' listing_id=id %}" method="POST">

Django TypeError when accessing a link by get_absolute_url()

Good day.
So i'm going through Django 2 by Example and i've encoutered a strange error when visiting a object from list of objects.
TypeError at /1/black-tea/
product_detail() got an unexpected keyword argument 'id'
The type it recieves is correct so small help would be appriciated.
code from views.py
def product_detail(request, product_id, slug):
product = get_object_or_404(Product, slug=slug,
id=product_id, available=True)
return render(request, 'shop/product/detail.html',
{'product': product})
models.py
class Product(models.Model):
category = models.ForeignKey(Category,
related_name='products',
on_delete=models.CASCADE)
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)
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('name',)
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])
urls.py
path('<int:id>/<slug:slug>/', product_detail, name='product_detail'),
Code from template
<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/images.jpeg' %}{% endif %}">
</a>
{{ product.name }}
<br>
${{ product.price }}
</div>
{% endfor %}
</div>
product_detail arguments should match your url mapping parameters in urls.py. The function definition should has arguments id, slug:
def product_detail(request, id, slug):
...

Categories

Resources