python - 使用 django 2 添加类别的 url

标签 python django categories django-2.0

我正在处理我的博客页面 基本上博客有用于拆分相同帖子的类别, 为了这 我为类别创建了一个类,并在类别和我的帖子类之间建立了关系,如下所示:

class Category(models.Model):
    name = models.CharField(max_length=256)

def __str__(self):
    return self.name


class Post(models.Model):
  image = models.ImageField(upload_to='Posts_image')
  title = models.CharField(max_length=256)
  configure_slug = models.CharField(max_length=512)
  slug = models.SlugField(max_length=512,null=True,blank=True)
  content = HTMLField('Content')
  date = models.DateTimeField(auto_now_add=True)
  categories = models.ManyToManyField(Category)
  tags = TaggableManager()
  publish = models.BooleanField(default=False)

  def __str__(self):
    return self.title

在此之后我做了这个功能

def blog_category(request):
  res_posts = Post.objects.all()
  category = request.POST.get('categories__name')
  if category:
    res_post = res_post.filter(
        Q(categories__name__icontains=category)).distinct()

  context = {
    'posts':res_posts,
  }
  return render(request, 'Blog/category-result.html', context)

我告诉你它是如何工作的: 当用户单击博客页面中的类别标题之一时 该函数开始工作并搜索有多少帖子具有此类别标题并将它们列在 category-result.html

但是这个函数不能正常工作 我认为这段代码无法正常工作

category = request.POST.get('categories__name')

当用户点击时,request.Post 无法获取categories__name

你能帮我解决这个问题吗???

最佳答案

正如您所说,用户点击,我假设类别标题链接到类似http://your.site/your-view?categories__name=selected-category,如果是这种情况,您需要使用的是 request.GET 而不是 request.POST

关于python - 使用 django 2 添加类别的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58392030/

相关文章:

php - 获取opencart主页上的产品类别

python - 一种使用行和列标题读取 CSV 的 Pythonic 方法

python - 带有 Splash 的 CrawlSpider

Django SSL 证书和静态媒体

Aptana Studio 3.0 上的 Django

css - Woocommerce - [product_categories] 简码 - 如何从列表中排除两个类别?

python - Flask 应用程序的导入问题

python - Pandas 使用 regex=true 替换部分单词

django - 在基于 Django 类的 View 中覆盖 get() 以进行过滤

iphone - 类别授权