我正在使用摘要创建菜单。
菜单项可以选择将内部页面作为目标页面,或将外部页面作为目标页面(例如google.com)。
内部选项很好用,但是外部选项在新标签中打开,主机名附加到外部链接:
http://127.0.0.1:8000/google.com
不确定我的Orderable
模型是否有问题或发生了什么。
代码:
class MenuItem(Orderable):
link_title = models.CharField(
blank=True,
null=True,
max_length=50
)
link_url = models.CharField(
max_length=500,
blank=True,
)
link_page = models.ForeignKey(
"wagtailcore.Page", #app y modelo de tu proyecto
blank=True,
null=True,
related_name="+",
on_delete=models.CASCADE,
)
open_in_new_tab = models.BooleanField(default=False, blank=True,)
page = ParentalKey("Menu", related_name="menu_items")
panels = [
FieldPanel("link_title"),
FieldPanel("link_url"),
PageChooserPanel("link_page"),
FieldPanel("open_in_new_tab"),
]
# @tood add properties
# link
@property
def link(self):
if self.link_page:
return self.link_page.url
elif self.link_url:
return self.link_url
return "#"
@property
def title(self):
if self.link_page and not self.link_title:
return self.link_page.title
elif self.link_title:
return self.link_title
return 'Missing title'
@register_snippet
class Menu(ClusterableModel):
title = models.CharField(max_length=100)
slug = AutoSlugField(populate_from="title", editable=True)
panels = [
MultiFieldPanel([
FieldPanel("title"),
FieldPanel("slug")
], heading="Menu"),
InlinePanel("menu_items", label="Menu item")
]
def __str__(self):
return self.title
html:
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul>
<li>
<a href="/">Home</a>
</li>
{% for item in navigation.menu_items.all %}
<li>
<a href="{{ item.link }}" class="nav-link" {% if item.open_in_new_tab %} target="_blank" {% endif %}>{{ item.title }}</a>
</li>
{% endfor %}
</ul>
<form class="form-inline ml-auto">
<a href="" class="btn btn-outline-secondary">Ingresar</a>
<a href="" class="btn btn-primary ml-2">Registro</a>
</form>
</div>
发现了另一个问题,但与我的方法有所不同:
Making external links open in a new window in wagtail
屏幕截图:
您的代码对我来说看起来很好。只是您输入的URL错误。您需要添加http(s)://
部分,以便链接实际上指向https://google.com
而不是http://127.0.0.1:8000/google.com
。
此外,我建议将link_url
从CharField
更改为URLField
,例如:
URLField
原因是,尽管两个字段相同,但是class MenuItem(Orderable):
# ...
link_url = models.URLField(
max_length=500,
blank=True,
)
具有内置逻辑(即URLField
),用于检查正确的URL模式。因此,当您在管理员中输入无效的URL(例如validator而不输入google.com
)时,菜单将不会保存。请记住,一旦替换了字段,请运行https://
和manage.py makemigrations
。