【问题标题】:How to create a link in the Django website如何在 Django 网站中创建链接
【发布时间】:2020-05-26 14:26:56
【问题描述】:

我正在开发 Django 博客。我在管理帖子中创建了一个 url 列,如下所示。

但是,当我单击页面中的链接时,页面会跳转到 URL 开头包含 localhost:8000 的链接。 例如http://127.0.0.1:8000/Yahoo/www.yahoo.com

我将链接设为<a href="{{ post.url }}">Visit yahoo.com!</a>,但这可能是一种错误的做法。 你能告诉我如何解决这个问题吗?

model.py 中我的类

class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
url = models.CharField(max_length=200, unique=True, default='')
class Meta:
    ordering = ['-created_on']

def __str__(self):
    return self.title

我的html

{% extends 'base.html' %} {% block content %}

<div class="container">
  <div class="row">
    <div class="col-md-8 card mb-4  mt-3 left  top">
      <div class="card-body">
        <h1>{% block title %} {{ object.title }} {% endblock title %}</h1>
        <p class=" text-muted">{{ post.author }} | {{ post.created_on }}</p>
        <p class=" text-muted">{{ post.url }}</p>

        <a href="{{ post.url }}">Visit yahoo.com!</a>

        <p class="card-text ">{{ object.content | safe }}</p>
      </div>
    </div>
    {% block sidebar %} {% include 'sidebar.html' %} {% endblock sidebar %}
  </div>
</div>

{% endblock 内容 %}

【问题讨论】:

  • 您需要在开头添加 url 方案(http:// 或 https://)位,以便浏览器能够确定 URL 不是相对的网站。
  • 酷!有效。非常感谢

标签: django


【解决方案1】:

http://127.0.0.1:8000/Yahoo/www.yahoo.com

这意味着您指定的链接是相对于您当前的路径:

<a href="{{ post.url }}">Visit yahoo.com!</a>

通过添加前缀斜杠使其绝对化也无济于事,因为它仍然会引用您当前正在运行的服务器

<a href="/{{ post.url }}">Visit yahoo.com!</a>

http://127.0.0.1:8000/www.yahoo.com

如果 post.url 在您的服务器外部且位于您的服务器之外,请附加前缀 http://https://

<a href="http://{{ post.url }}">Visit yahoo.com!</a>

【讨论】:

  • 太棒了。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2011-03-23
  • 2018-05-13
  • 1970-01-01
  • 2018-01-10
  • 1970-01-01
  • 2017-08-27
  • 2010-11-03
  • 1970-01-01
相关资源
最近更新 更多