Django应用程序部署在郊区,登录后重定向到主页

时间:2015-09-03 21:07:59

标签: python django apache

我的页面部署在http://example.com。我还在http://example.com/djangoapp部署了我的django应用程序。

我使用Apache 2.2使用此配置(/etc/apache2/apache2.conf):WSGIPythonPath /home/brian/djangoprojects/djangoapp

我还将行WSGIScriptAlias /djangoapp /home/brian/djangoprojects/djangoapp/djangoapp/wsgi.py添加到默认的Apache Virtual Host文件中,它的效果非常好。

但是,登录后,我的应用程序会将我重定向到http://example.com/而不是http://example.com/djangoapp/homeit

这是我的urls.py文件:

from django.conf.urls import include, url
from django.contrib import admin
from djangoapp import views

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', 'django.contrib.auth.views.login', name="login"),
    url(r'^logout/$', views.logout_page, name="logout"),
    url(r'^accounts/login/$', 'django.contrib.auth.views.login', name="login"),
    url(r'^register/$', views.register, name="register"),
    url(r'^register/success/$', views.register_success, name="register_success"),
    url(r'^homeit/$', views.homeit, name="homeit"),
]

这是我的views.py文件:

from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
from django.contrib.auth.models import User
from django.views.decorators.csrf import csrf_protect
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.core.urlresolvers import reverse
from djangoapp.forms import RegistrationForm


@csrf_protect
def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password1'],
                email=form.cleaned_data['email']
            )
            return HttpResponseRedirect(reverse('register_success'))
    else:
        form = RegistrationForm()
    variables = RequestContext(request, {
        'form': form
    })

    return render_to_response(
        'registration/register.html',
        variables,
    )


def register_success(request):
    return render_to_response('registration/success.html')


def logout_page(request):
    logout(request)
    return HttpResponseRedirect(reverse('login'))


@login_required
def homeit(request):
    return render_to_response(('home.html', {'user': request.user}))

我的设置文件settings.py

LOGIN_URL = '/djangoapp/accounts/login/'
USE_X_FORWARDED_HOST = True
SUB_SITE = "/djangoapp"

最后,我用来登录的登录页面:

{% extends "base.html" %}
{% block title %}Login{% endblock %}
{% block head %}Login{% endblock %}
{% block content %}
    {% if form.errors %}
        <p>Your username and password didn't match. Please try again.</p>
    {% endif %}
    <form method="post" action=".">{% csrf_token %}
        <table border="0">
            <tr><th><label for="id_username">Username:</label></th><td>{{ form.username }}</td></tr>
            <tr><th><label for="id_password">Password:</label></th><td>{{ form.password }}</td></tr>
        </table>
        <input type="submit" value="Login" />
        <input type="hidden" name="next" value="{% url "homeit" %}" />
    </form>
    <a href="{% url "register" %}">Register</a>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

快速阅读

解决此问题的方法:

  • 在settings.py
  • 中添加LOGIN_REDIRECT_URL = '/djangoapp/homeit'
  • 将您的urls.py9更改为url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'extra_context': {'next':'/djangoapp/homeit'}}),

说明

检查django.contrib.auth.views.login的文档here

def login的代码如下:

def login(request, template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm,
          current_app=None, extra_context=None):
    """
    Displays the login form and handles the login action.
    """
    redirect_to = request.POST.get(redirect_field_name,
                                   request.GET.get(redirect_field_name, ''))

    if request.method == "POST":
        form = authentication_form(request, data=request.POST)
        if form.is_valid():

            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

            # Okay, security check complete. Log the user in.
            auth_login(request, form.get_user())

            return HttpResponseRedirect(redirect_to)
    else:
        form = authentication_form(request)

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }
    if extra_context is not None:
        context.update(extra_context)

    if current_app is not None:
        request.current_app = current_app

    return TemplateResponse(request, template_name, context)

发生了什么:

  • django.contrib.auth.views.login需要redirect_field_name并相应地重定向
  • redirect_field_name的默认值为next
  • 目前,由于您未将任何内容作为next参数传递,因此会自动生成redirect_to = ''
  • HttpResponseRedirect被称为HttpResponseRedirect('')
  • 因此,它最终会重定向到您的主页,而不是/djangoapp