Django 无法正确重定向

Django fails to redirect properly

我是 Django 的新手,正在做一个 URL 缩短项目,比如 bitly。当我尝试单击在 success.html 模板中创建的 link 时,我 运行 遇到了问题,它没有重定向,而是附加了路径 + short_url + url:

DEBUG-URLRedirectView::get(): obj.url: www.google.com
[05/Feb/2017 19:02:27] "GET /gesw1m/ HTTP/1.1" 302 0
Not Found: /gesw1m/www.google.com
[05/Feb/2017 19:02:27] "GET /gesw1m/www.google.com HTTP/1.1" 404 2216

这是项目树:

-src_shrtnr
   manage.py
   -shrtnr
      hosts.py
      settings.py
      urls.py
      -hostconf
         urls.py
         views.py
   -shortener
      models.py
      views.py
      -templates
         -shortener
            already-exist.html
            home.html
            success.html
   -analytics
      ...

这是 success.html 模板和图像:

<div style='align-text: center; width: 800px; margin: 0 auto;'>
    <h1>Created!</h1>
    <p>{{ object.url }}</p>
    <p>Count: {{ object.clickevent.count }}</p>
    <p><a href='{{ object.get_short_url }}'>{{ object.get_short_url }}</a></p>
    <a href='/'>+New</a>
</div>

这是缩短器 models.py 文件:

class ShrtnrURL(models.Model):
    url = models.CharField(max_length=220, validators=[validate_url, validate_dot_com])
    shortcode = models.CharField(max_length=SHORTCODE_MAX, unique=True, blank=True)

    ...

    def get_short_url(self):
        url_path = reverse('scode', kwargs={'shortcode': self.shortcode}, host='www', scheme='http')
        print('DEBUG-ShrtnrURL::get_short_url(), url_path: ', url_path)
        return url_path

这里是缩短器views.py相关视图:

class URLRedirectView(View):
        qs = ShrtnrURL.objects.filter(shortcode__iexact=shortcode)
        if qs.count() != 1 and not qs.exists():
            raise Http404
        obj = qs.first()
        print('DEBUG-URLRedirectView::get(): obj.url: ',ClickEvent.objects.create_event(obj), obj.url)
        return HttpResponseRedirect(obj.url)

这是主机配置urls.py:

from .views import wildcard_redirect

urlpatterns = [
    url(r'^(?P<path>.*)', wildcard_redirect),
]

这是主机配置views.py:

DEFAULT_REDIRECT_URL = getattr(settings, 'DEFAULT_REDIRECT_URL', 'http://www.shrtnr.co')

def wildcard_redirect(request, path=None):
    new_url = DEFAULT_REDIRECT_URL
    if path is not None:
        new_url = DEFAULT_REDIRECT_URL + '/' + path
    print('DEBUG-wildcard_redirect(), new_url: ', new_url)
    return HttpResponseRedirect(new_url)

这里是hosts.py:

from shrtnr.hostsconf import urls as redirect_urls
host_patterns = [
    host(r'www', settings.ROOT_URLCONF, name='www'),
    host(r'(?!www).*', redirect_urls, name='wildcard'),
]

这里是 shrtnr urls.py:

from shortener.views import HomeView, URLRedirectView
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', HomeView.as_view()),
    url(r'^(?P<shortcode>[\w-]+)/$', URLRedirectView.as_view(), name='scode'),
]

选自 settings.py 的部分:

ALLOWED_HOSTS = ['www.shrtnr.co', 'shrtnr.co', 'blog.shrtnr.co']
INSTALLED_APPS = [
    ...
    # Third party
    'django_hosts',
    # Custom app
    'analytics',
    'shortener',
]
MIDDLEWARE = [
    'django_hosts.middleware.HostsRequestMiddleware',
    ...
    'django_hosts.middleware.HostsResponseMiddleware',
]
ROOT_URLCONF = 'shrtnr.urls'
ROOT_HOSTCONF = 'shrtnr.hosts'
DEFAULT_HOST = 'www'
DEFAULT_REDIRECT_URL = 'http://www.shrtnr.co:8000'
PARENT_HOST = 'shrtnr.co:8000'

只是指出我在 /etc/hosts 中添加:

127.0.0.1 www.shrtnr.co
127.0.0.1 shrtnr.co
127.0.0.1 blog.shrtnr.co

我仍然处于 "debug" 模式,还没有托管(将使用 Heroku),但我在 settings.py 中根据需要添加了 :8000 端口。 我想我添加了所有必要的信息,如果我忘记提及某些内容,请告诉我。一旦我托管它可能会解决,但我不确定。

问题是您的 URL 只是 "www.google.com",没有协议。当浏览器被告知重定向时,如果没有协议,它只是将其视为路径 - 由于也没有初始斜杠,它将把它视为相对路径并将其附加到当前位置。

您可能需要添加验证以确保该字段包含完整的 URL 包括协议,即“https://www.google.com”。或者,您的视图可能会检查值并在必要时添加 "http://" 或 "https://"。