Can't get the detail view of a post in a social network project

二次信任 提交于 2020-05-17 07:15:06

问题


I am building a simple social network in django.

In the "home" of my social, I have the list of all posts published by all users, with author and publishing date. The publishing date have a link to a url that should return the detail view of a specific post published by a user.

However, as I click on it, it shows me the list of all posts published by its author (this also works when I click on the author link of the post).

So both

www.mysocial.com/posts/by/ciccio/7/

and

www.mysocial.com/posts/by/ciccio/

take me to the same page, that is ciccio's posts list.

I am going to show urls.py, views.py and models.py that all are contained in my "posts" app (myproject > posts)

Here is my urls.py

# shows all user posts
url(r'by/(?P<username>[-\w]+)', 
views.UserPosts.as_view(), 
name='for_user'),

# shows specific post
url(r'by/(?P<username>[-\w]+)/(?P<pk>\d+)/$', 
views.PostDetail.as_view(), 
name='single'),

my views.py

class PostList(SelectRelatedMixin, generic.ListView):
    model = Post
    select_related = ('user', 'group')

class UserPosts(generic.ListView):
    model = models.Post
    template_name = 'posts/user_post_list.html'

    def get_queryset(self):
        try:
            #prende i post fatti dal'username che è lo stesso di quello che è loggato per guardarli
            self.post_user = User.objects.prefetch_related('posts').get(username__iexact=self.kwargs.get('username'))

        except User.DoesNotExist:
            raise Http404

        else:
            return self.post_user.posts.all()

    def get_context_data(self,**kwargs):
        context = super().get_context_data(**kwargs)
        context['post_user'] = self.post_user
        return context

class PostDetail(SelectRelatedMixin, generic.DetailView):
    model = models.Post
    select_related = ('user', 'group') #group senza apostrofo?

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(
            user__username__iexact=self.kwargs.get('username'),
            # maybe smth is needed here?
            )

my models.py

User = get_user_model()


# Create your models here.

class Post(models.Model):
    user = models.ForeignKey(User, related_name="posts", on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now=True)
    message = models.TextField()
    message_html = models.TextField(editable=False)


    group = models.ForeignKey(Group, related_name="posts", null=True, blank=True, on_delete=models.CASCADE)

    def __str__(self):
        return self.message

    def save(self, *args, **kwargs):
        self.message_html = m.html(self.message)
        # in questo modo quando si fa un markdon si mette un link nel loro post
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('posts:single', kwargs={'username':self.user, 'pk':self.pk})

    class Meta:
            ordering = ['-created_at']
            unique_together = ['user', 'message'] 

my piece of template showing author and publishing date of a post:

    <span class="username">
        <!--  mi porta a tutti i post fatti da quell'user -->
        <a href="{% url 'posts:for_user' username=post.user.username %}">@{{ post.user.username }}</a>
    </span>

    <a> – </a>

    <!-- il time tag posta il tempo -->
    <time class="time">
    <a href="{% url 'posts:single' username=post.user.username pk=post.pk %}">{{ post.created_at }}</a>

    </time>

The model "User" is django's default models.User

The problem must be in PostDetail view, since I verified that by clicking on the url, my template shows the post correct pk (post.pk)

Maybe a filter is missing in views? see my # comment


回答1:


A /$ was missing at the end of the first url:

url(r'by/(?P<username>[-\w]+)/$', 
    views.UserPosts.as_view(), 
    name='for_user'),

But I still can't understend how could the url used to display the view showing all users's posts influence the behaviour of the url that should show only a specific post.



来源:https://stackoverflow.com/questions/61238712/cant-get-the-detail-view-of-a-post-in-a-social-network-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!