我正在构建相册应用。用户可以在其中登录并创建类别,并在这些类别中添加照片帖子。
单击帖子链接时,它应该使用DetailView来打开帖子,它只是通过帖子链接循环回到用户的帖子历史记录页面
我一直在尝试使用各种方法来过滤查询集并返回数据,但是我没有错。
posts / models.py:
class Post(models.Model):
user = models.ForeignKey(User, related_name='posts',on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now=True)
post_title = models.CharField( max_length=30)
post_message = models.TextField()
postimage = models.ImageField(upload_to='postimgs/',verbose_name=('post picture'))
category = models.ForeignKey(Category, related_name='post_category', on_delete=models.CASCADE)
def __str__(self):
return self.post_title
def save(self,*args,**kwargs):
self.post_message_html = misaka.html(self.post_message)
super().save(*args,**kwargs)
def get_absolute_url(self):
return reverse('posts:single', kwargs={"username":self.user.username,"pk":self.pk})
class Meta:
ordering = ['-created_at']
unique_together = ['user','post_title']
posts / views.py:
class PostDetail(SelectRelatedMixin, generic.DetailView):
model =models.Post
select_related = ('user', 'category')
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(user__username__iexact=self.kwargs.get('username'))
posts / urls.py:
app_name = 'posts'
urlpatterns = [
url(r'^$',views.PostList.as_view(),name='all'),
url(r'new/$',views.CreatePost.as_view(),name='create'),
url(r'by/(?P<username>[-\w]+)',views.UserPosts.as_view(),name='for_user'),
url(r'by/(?P<username>[-\w]+)/(?P<pk>\d+)/$',views.PostDetail.as_view(),name='single'),
url(r'delete/(?P<pk>\d+)/$',views.DeletePost.as_view(),name='delete'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
HTML:
<a href="{% url 'posts:for_user' username=post.user.username%}">@{{post.user.username}}</a>
</span>
<time class="time">
<a href="{% url 'posts:single' username=post.user.username pk=post.pk %}">
{{post.created_at}}
</a>
点击{{post.created_at}}后,应该会打开带有详细信息的帖子详细信息视图,但它会在帖子列表页面中循环显示
答案 0 :(得分:1)
您的查询集缺少comma(',')
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(user__username__iexact=self.kwargs.get('username'),category__categoryname__iexact=self.kwargs.get('categorynamee'))
并更改您的网址并在前面添加^
url(r'^new/$',views.CreatePost.as_view(),name='create'),
url(r'^by/(?P<username>[-\w]+)',views.UserPosts.as_view(),name='for_user'),
url(r'^by/(?P<username>[-\w]+)/(?P<pk>\d+)/$',views.PostDetail.as_view(),name='single'),
url(r'^delete/(?P<pk>\d+)/$',views.DeletePost.as_view(),name='delete'),