samedi 1 février 2020

Obtaining the blog post like feature and capturing slug of the page

I'm trying to figure out the "Like" feature of this blog, i.e. Liking a particular blog post. Kindly help, I'm really stuck here. Here are the files and the error.

models.py

class Posts(models.Model):
    author= models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE)
    likes= models.ManyToManyField(settings.AUTH_USER_MODEL, blank= True, related_name='likes')
    published_time= models.DateTimeField(auto_now_add=True, blank=True)
    title= models.CharField(blank=False, editable=True, max_length=255)
    slug= models.SlugField(max_length=255, blank= True, null= True,allow_unicode=True, unique= True)
    updated= models.DateTimeField(auto_now=True, blank= True)
    content= models.CharField(default=False, max_length=10000,editable=True)

    widgets= {
        'title': forms.TextInput(attrs={'class' :'textinputclass'}),
        'content': forms.TextInput(attrs= {'class':'textinputclass text-area-style' }),
    }

    def get_absolute_url(self): 
        return reverse(
            'postdetail',
            kwargs={'slug': self.slug}) 

    def get_like_url(self):
        return reverse('like', kwargs={"slug": self.slug})

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.slug = self.slug or slugify(self.title)
        super().save(*args, **kwargs)

Here in the models I've added a field "likes" which will hold the users who have liked this particular post. Notice it has a get_like_url() method. I call the method in the HTML template like this.

posts_detail.html

<body style="width: 60%; margin: 0 auto; background-color: rgb(205, 249, 255);">
    <div class="box-style">
        <h1 class="heading-text"></h1> <br>
        <div class="poem-text">
           <pre></pre> 
        </div>
        <br>
        <div class="footer-text">
            <p>Author:  
                <br> Posted On: 
            </p>
            <br>
        </div>
            ***<a href="  " class="btn btn-danger">Like  </a>***
    </div>
</body>

It takes me to the url named 'likes'. Here is the urls.py which I think is the problem.

urls.py

urlpatterns= [
    path('create/', views.PostCreate.as_view(), name='createpost' ),
    path('<slug:slug_url>', views.PostDetail.as_view(), name= 'postdetail'),
    path('postlist/', views.PostList.as_view(), name='postlist'),
    path('likes/$', views.PostLikeToggle, name= 'like')
]

views.py

class PostDetail(DetailView):
    model= Posts
    slug_url_kwarg= 'slug_url'
    slug_field= 'slug'

class PostLikeToggle(RedirectView):
    def get_redirect_url(self, *args, **kwargs):
        slug = self.kwargs.get("slug")
        print(slug)
        obj = get_object_or_404(Posts, slug=slug)
        print(obj.likes.count)
        url_ = obj.get_absolute_url()
        user = self.request.user
        if user.is_authenticated():
            if user in obj.likes.all():
                obj.likes.remove(user)
            else:
                obj.likes.add(user)
        return url_

Here is the error I'm getting.

Error

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/post/dogs-are-cute

Django Version: 2.2.4
Python Version: 3.7.4
Installed Applications:
['authentica.apps.AuthenticaConfig',
 'post.apps.PostConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']


Template error:
In template D:\authen\post\templates\post\posts_detail.html, error at line 54
   Reverse for 'like' with keyword arguments '{'slug': 'dogs-are-cute'}' not found. 1 pattern(s) tried: ['post/(?P<slug_url>[-a-zA-Z0-9_]+)/$']
   44 :         <div class="poem-text">
   45 :            <pre></pre> 
   46 :         </div>
   47 :         <br>
   48 :         <div class="footer-text">
   49 :             <p>Author:  
   50 :                 <br> Posted On: 
   51 :             </p>
   52 :             <br>
   53 :         </div>
   54 :             <a href="    " class="btn btn-danger">Like  </a>
   55 :     </div>
   56 : </body>
   57 : </html>

Traceback:

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  145.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  143.                 response = response.render()

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py" in render
  106.             self.content = self.rendered_content

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py" in rendered_content
  83.         content = template.render(context, self._request)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\backends\django.py" in render
  61.             return self.template.render(context)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py" in render
  171.                     return self._render(context)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py" in _render
  163.         return self.nodelist.render(context)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py" in render
  937.                 bit = node.render_annotated(context)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py" in render_annotated
  904.             return self.render(context)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py" in render
  987.             output = self.filter_expression.resolve(context)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py" in resolve
  671.                 obj = self.var.resolve(context)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py" in resolve
  796.             value = self._resolve_lookup(context)

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\base.py" in _resolve_lookup
  858.                             current = current()

File "D:\authen\post\models.py" in get_like_url
  37.         return reverse('like', kwargs={"slug": self.slug})

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\base.py" in reverse
  90.     return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))

File "C:\Users\hello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix
  668.         raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /post/dogs-are-cute
Exception Value: Reverse for 'like' with keyword arguments '{'slug': 'dogs-are-cute'}' not found. 1 pattern(s) tried: ['post/(?P<slug_url>[-a-zA-Z0-9_]+)/$']

I also want to know if the approach is right or not? Also, how can I use JavaScript to trigger the views, if it's possible? Please HELP! :( Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire