我有一个包含 3 个字段(名称、网址、日期)的模型。如何在 View 中获取 url 并将其放入方法中?
sites = Site.objects.all().order_by('date')[:3]
我需要从 url(http://www.example.com 到 example.com)获取主机。我有一个用于此任务的类(class):
class SiteThumb():
def get_site_thumb(self, url):
host = urlparse(url).hostname
if host.startswith('www.'):
host = host[4:]
return(host)
我想稍后在我的模板中使用它(类似于 {{ site.url }} 但使用与特定“站点”对象相关的变量“主机”)。我无法处理它。我可以使用另一种 View ,其中只有一个站点:
def site(request, category_slug, subcategory_slug, id):
我可以简单地将 id 分配给特定对象。在我的基本 View 中
def index(request):
我必须加载几个对象。感谢您提供任何线索。
最佳答案
一种方法是模型方法。
例如。 Site
是一个模型,其中包含上述三个字段 url、名称和日期。现在您可以为 Site
模型定义一个模型方法,您可以在模板中访问该方法。可以按照这样的方式来完成。
class Site(models.Model):
url = field
name = field
date = field
def hostname(self):
#It is copy paste of your implementation
host = urlparse(url).hostname
if host.startswith('www.'):
host = host[4:]
return host
在每个 Site
实例上的模板中,可以通过 {{ site.hostname }}
访问此方法。
关于django - 从 django 模型获取值以便在 View 中进一步使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41864184/