Home > Software engineering >  django error : NoReverseMatch at /watchlist/ Reverse for 'viewList' with arguments '(
django error : NoReverseMatch at /watchlist/ Reverse for 'viewList' with arguments '(

Time:11-06

I am working on my project and the main idea is to add some items to the watchlist or "bookmark" some items:

when I render the page to see the watchlist that I add them by clicking on the "Add to watchlist button " Django give me this error: NoReverseMatch at /watchlist/ Reverse for 'viewList' with arguments '('',)' not found. 1 pattern(s) tried: ['Post/(?P[0-9] )$']

my code:

Model.py file

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')
         path('Post/<int:id>', views.viewList, name='viewList'),

]

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 FILE: (item.html) this file for showing the post for exapmple : (title/ description/ date etc..)

   <!-- 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 FILE (layout.html) for adding a link to the navbar for the page

            <li class="nav-item">
                <a class="nav-link" href="{% url 'watchlist_list' %}">Watchlist</a>
            </li>

HTML FILE(whitchlsit page)

        {% 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 %}

CodePudding user response:

The culprit of this problem is that you are calling "{% url 'viewList' listing.id %}" even though viewList does not exist in your urls.py.

So, you can create one like this:

path("some/path", views.some_func, name="viewList")

EDIT

As the error says, listing.id is empty ({% url 'viewList' listing.id %}). So, you might want to do post.id instead because you are looping with the name of post.

  • Related