Ошибка django : NoReverseMatch at /watchlist/ Reverse for 'viewList' with arguments '('',)'
Я работаю над своим проектом и основная идея состоит в том, чтобы добавить некоторые элементы в список просмотра или "закладку" некоторых элементов:
когда я отображаю страницу, чтобы увидеть список часов, которые я добавил в него, нажав на кнопку "Добавить в список часов", Django выдает мне эту ошибку: NoReverseMatch at /watchlist/ Reverse for 'viewList' with arguments '('',)' not found. Попробовано 1 шаблон(ы): ['Post/(?P[0-9]+)$']
мой код:
Файл Model.py
class Post(models.Model):
#data fields
title = models.CharField(max_length=64)
textarea = models.TextField()
#bid
price = models.FloatField(default=0)
currentBid = models.FloatField(blank=True, null=True)
imageurl = models.CharField(max_length=255, null=True, blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, default="No Category Yet!", null=True, blank=True)
creator = models.ForeignKey(User, on_delete=models.PROTECT)
date = models.DateTimeField(auto_now_add=True)
# for activated the Category
activate = models.BooleanField(default=True)
buyer = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name="auctions_Post_creator")
############################### this is the watchers
watchers = models.ManyToManyField(User, blank=True, related_name='favorite')
def __str__(self):
return f"{self.title} | {self.textarea} | {self.date.strftime('%B %d %Y')}"
urls.py
urlpatterns =[
# Watchlist
path('Post/<int:id>/watchlist_post/change/<str:reverse_method>',
views.watchlist_post, name='watchlist_post'),
path('watchlist/', views.watchlist_list, name='watchlist_list')
]
views.py
#start watchlist
def viewList(request, id):
# check for the watchlist
listing = Post.objects.get(id=id)
if listing.watchers.filter(id=request.user.id).exists():
is_watched = True
else:
is_watched = False
context = {
'listing': listing,
'comment_form': CommentForm(),
'comments': listing.get_comments.all(),
'Bidform': BidForm(),
# IS_WATCHED method
'is_watched': is_watched
}
return render(request, 'auctions/item.html', context)
@login_required
def watchlist_post(requset, id, reverse_method):
listing = get_object_or_404(Post, id=id)
if listing.watchers.filter(id=requset.user.id).exists():
listing.watchers.remove(requset.user)
else:
listing.watchers.add(requset.user)
if reverse_method == "viewList":
return viewList(requset, id)
return HttpResponseRedirect(reverse(reverse_method))
@login_required
def watchlist_list(request):
user = requset.user
watchers_items = user.favorite.all()
context = {
'watchers_items': watchers_items
}
return render(requset, 'auctions/watchlist.html', context)
HTML ФАЙЛ: (item.html) этот файл для отображения поста, например: (заголовок/описание/дата и т.д.)
<!-- check to add to watchlist -->
<div class="col">
{% if is_watched %}
<a href="{% url 'watchlist_post' listing.id 'viewList' %}" class="btn btn-dark btn-sm m-1 btn-block">Remove To Watchlist</a>
<!-- remove it -->
{% else %}
<a href="{% url 'watchlist_post' listing.id 'viewList' %}" class="btn btn-dark btn-sm m-1 btn-block">Add To Watchlist</a>
{% endif %}
</div>
HTML-файл (layout.html) для добавления ссылки на навигационную панель для страницы
<li class="nav-item">
<a class="nav-link" href="{% url 'watchlist_list' %}">Watchlist</a>
</li>
HTML FILE (страница whitchlsit)
{% for post in watchers_items %}
<div class="col-sm-4">
<div class="card my-2">
<img src="{{post.imageurl}}" class="img-fluid">
<div class="card-body">
<div class="text-center py-2">
<h5 class="card-title text-info">{{post.title}}</h5>
<p class="alert alert-info">{{post.textarea}}</p>
<ul class="list-group">
<li class="list-group-item list-group-item-info">category: {{post.category.name}}</li>
<li class="list-group-item list-group-item-info">Price: {{post.price}}$</li>
<li class="list-group-item list-group-item-info">Created by: {{post.creator}}</li>
</ul>
</div>
<!-- Buttons -->
<div class="row">
<div class="col">
<a href="{% url 'viewList' listing.id %}" class="btn btn-dark btn-sm m-1 btn-block">View</a>
</div>
</div>
</div>
<div class="card-footer">
<small class="text-muted">Created since:{{post.date}}</small>
</div>
</div>
{% endfor %}
Виновником этой проблемы является то, что вы вызываете "{% url 'viewList' listing.id %}"
, хотя viewList
не существует в вашем urls.py
.
Итак, вы можете создать его следующим образом:
path("some/path", views.some_func, name="viewList")
EDIT
Как гласит ошибка, listing.id
пуст ({% url 'viewList' listing.id %}
). Поэтому, возможно, вы захотите сделать post.id
вместо этого, потому что вы зацикливаетесь с именем post
.