Django:重定向到存储在 dB 中的外部 URL

Django: redirecting to an external URL stored in the dB

我正在构建 Django 应用程序。我的最终目标是让用户能够单击 link 以重定向到外部站点。这是我的代码:

models.py

class Entry(models.Model):
    manufacturer = models.CharField(max_length=255)
    source_url = models.URLField(blank=True)

views.py

def purchase(request, entry_id):
    entry = get_object_or_404(Entry, pk=entry_id)
    return redirect(entry.source_url)

entry.html

{% if user.is_authenticated %}
    <a href="{% url 'purchase' %}">Purchase!</a>
{% endif %}

urls.py

urlpatterns = [
    path('', views.index, name='index'),
    path('entries/<int:entry_id>', views.entry, name='entry'),
]

数据库中的数据如下所示:

id    manufacturer     source_url
1     Mercedes         https://www.mbusa.com/en/home
2     BMW              https://www.bmw.com/en/index.html
3     Audi             https://www.audiusa.com/us/web/en.html

我收到的错误消息是:

Exception Value:    
Reverse for 'purchase' not found. 'purchase' is not a valid view function or pattern name.

作为测试,我更改了以下代码行:

发件人:<a href="{% url 'purchase' %}">Go to Source!</a>

收件人:<a href="www.google.com">Go to Source!</a>

这消除了“反向”错误,但它创建的 URL 是:

http://127.0.0.1:8000/entries/www.google.com

urls.py中缺少“购买”的URL路径导致的“逆向”错误吗?如果是,我将如何定义它?

在此先感谢您帮助这位 Django 新手!

要从视图重定向,您可以这样做:

from django.http import HttpResponseRedirect
def purchase(request, entry_id):
    entry = get_object_or_404(Entry, pk=entry_id)
    return HttpResponseRedirect(entry.source_url)

您可以通过以下方式解决 <a href="www.google.com">Go to Source!</a> 问题:

<a href="http://www.google.com">Go to Source!</a>

entry.html

{% if user.is_authenticated %}
    <a href="{% url 'purchase' entry_id %}">Purchase!</a>
{% endif %}

此处 entry_id 将是您的条目 Table 的主键。

urls.py

urlpatterns = [
    path('', views.index, name='index'),
    path('entries/<int:entry_id>', views.entry, name='entry'),
    path('purchase/<int:entry_id>', views.purchase, name='purchase'),
]