python - django模型方法中的get_full_path

标签 python django

我刚刚开始使用 django(老实说,还有 python)

我正在尝试获取一个模型方法,该方法可以从当前 URL 中删除 self.slug 并将其返回到模板。

这是我尝试过的方法:

class Category(models.Model):
    ...
    def remove_filter(self):
        url = HttpRequest.get_full_path()
        slug = '/' + self.slug
        return url.replace(slug, '')

但正如你可以想象的那样,它不起作用。

模板的片段:

{% for object in active_filters %}
    <li><a href="{{ object.remove_filter }}"><i class="icon-remove"></i></a>{{ object }}</li>
{% endfor %}

我的核心目标是通过删除当前对象的 slug 来更改其 url 的前端图标。

我不知道如何通过 View 来做到这一点,但我愿意接受任何建议。

def category_page(request, url):
    slugs = url.split('/')
    active = Category.objects.filter(slug__in=slugs)
    sorted_slugs = []
    for i in active:
        sorted_slugs.append(i.slug)
    if slugs != sorted_slugs:
        url = '/'.join(sorted_slugs)
        return redirect('http://127.0.0.1:8000/catalog/' + url)
    inactive = Category.objects.exclude(slug__in=slugs)
    return render(request, 'category.html', {'active_filters': active,
                                              'inactive_filters': inactive})

谢谢。

最佳答案

您可以将所有事件 slugs 的列表发送到模板,然后构建自定义模板过滤器来构造修改后的 URL。

views.py

# Send your list of active slugs to the template

return render(request, 'category.html', {
    'active_filters': active,
    'inactive_filters': inactive,
    'slugs': slugs,
})

tags_and_filters.py

import copy

from django import template

register = template.Library()


@register.filter(name='remove_filter')
def remove_filter(category, slugs): 
    copied_slugs = copy.copy(slugs)
    slug = category.slug
    if slug in copied_slugs:
        copied_slugs.remove(slug)
    return '/'.join(copied_slugs)

你的模板

{% for object in active_filters %}
<li>
  <a href="{{ object|remove_filter:slugs }}"><i class="icon-remove"></i></a>{{ object }}
</li>
{% endfor %}

关于python - django模型方法中的get_full_path,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14015701/

相关文章:

python - Positional ,关键字,可选和必需参数之间的区别?

python - django rest框架基于自定义类反序列化对象

javascript - 对 Django 的 Ajax 请求返回 404 not found

python - 多图片背景matplotlib

python - 从输出中删除 'None'

python - 无法从 Docker 容器访问本地主机

python - Rest API 应用程序在 'Sandbox' 但不是 'Live' 工作

python - 为什么这段代码在 Linux 上有效,但在 Windows 上却无效?

python - Django 应用程序尚未加载 Celery 任务

python - django 插入 Oracle 数据库无效标识符