1

Django 1.5 - django-ldap-auth

试图弄清楚如何正确使用 request_to_context 因为它只适用于 login.html 页面本身。(user.is_authenticated 等)。

用户登录后,它会将用户转发到 /reboot。从那里我想使用 {{ user.is_authenticated }} / {{ user.username }},但没有显示(真或假)。它只是空白。

在 login.html 页面本身上,它们可以正常工作。如果我渲染到 reboot/index.html 它不会渲染我拥有索引的代码。我假设我可以在用户通过身份验证后调用这些命令。希望我只是错过了这个难题的一小部分。

我已经包含了所有必要的代码。让我知道您是否需要其他东西。

这是我的布局。

重启/form.py

from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm

class LoginForm(forms.Form):
    username    = forms.CharField(label=(u'User Name'))
    password    = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))

视图.py

from django.template import Context, loader, RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect
from servers.models import Server
from reboot.forms import LoginForm
import paramiko
import socket

def logout_user(request):
    logout(request)
    return HttpResponseRedirect('/status/')

def index(request):
  t = loader.get_template('reboot/index.html')
  servers = Server.objects.all()
  c = Context( {
    'servers': servers,
  })
  return HttpResponse(t.render(c))

def test_ssh_liveness(ssh, name):
  try:
    ssh.connect(name, timeout='1')
    return True
  except socket.timeout:
    # server is down
    return False
  except socket.gaierror:
    # invalid server name
    return False
  except paramiko.SSHException:
    # unknown host key
    return True

def server(request, name):
  ssh = paramiko.SSHClient()
  is_alive = test_ssh_liveness(ssh, name)
  return HttpResponse("You selected server "+name+" and it is "+str(is_alive))

# user login
def login_user(request):
    if request.user.is_authenticated():
        # return HttpResponseRedirect('/reboot/')
        pass
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/reboot/')
        else:
            return render_to_response('login.html', {'form', form}, context_instance=RequestContext(request))
    else:
        ''' user is not submitting the form, show the login form '''
        form = LoginForm()
        context = {'form': form}
        return render_to_response('login.html', context, context_instance=RequestContext(request))

重启.urls

from django.conf.urls import patterns, url     
from reboot import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    #(r'^$', views.login_user),
    url(r'^server/(?P<name>[^/]+)', views.server, name='server')
)

主网址文件

from django.conf.urls import patterns, include, url 
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),

    url(r'^reboot/', include('reboot.urls')),
    # Login for reboot 
    (r'^login/$', 'reboot.views.login_user'),
    (r'^logout/$', 'reboot.views.logout_user'),

    url(r'^status/', include('status.urls')),
)

登录.html

% extends "base.html" %}
{% block content %}
<p> print {{ user.is_authenticated }}</p>
    <div id="login">
        <form class="form-horizontal" name="LoginForm" action="/login/" method="post">
        {% csrf_token %}
        {% if next %}
            <input type="hidden" name="next" value="{{ next }}" />
        {% endif %}

        <div class="control-group">
            <label class="control-label" for="username">Username</label>
            <div class="controls">
                <input type="text" id="username" name="username" placeholder="Username">
            </div>
        </div>

        <div class="control-group">
            <label class="control-label" for="password">Password</label>
            <div class="controls">
                <input type="password" name="password" id="password" placeholder="Password">
            </div>
        </div>

        <div class="control-group">
            <div class=controls">
                <button type="submit" class="btn">Login</button>
            </div>
        </div>

        </form>
    </div>

{% endblock %}

/reboot/index.html

{% extends "base.html" %}

{% block title %}Server{% endblock %}

{% block content %}
<h2>Server Control Panel</h2>
<h4>Welcome, print {{ user.is_authenticated }}.</h4>
{% if user.is_authenticated %}<p><a href="/logout/">Logout</a></p>{% else %}<a href="/login/">Login</a></p>{% endif %}
    <p class="lead">
    The servers below correspond to servers that you have access to. 
    If you believe there are errors, please <a href="mailto:jz@tripadvisor.com">contact me.</a>
    </p>
<div class="container-fluid">
<table class="table table-hover">
  <thead>
    <tr>
        <th><h4>Hostname</h4></th>
        <th><h4>Commands</h4></th>
    </tr>
  </thead>
  <tbody>
  {% for server in servers %}
    <tr>
        <td><a href="{% url 'server' server.hostname %}" class="btn">{{ server.hostname }}</a></td>
        <td>
            <a href="#" class="btn btn-success">start</a>
            <a href="#" class="btn btn-warning">restart</a>
            <a href="#" class="btn btn-danger">shutdown</a>
        </td>
    </tr>
  {% endfor %}
  </tbody>
</table>
</table>
</div>
{% endblock %}

我感谢您的所有帮助。我已经在这个问题上停留了几天,一直无法弄清楚。

约翰

4

1 回答 1

3

您的视图需要一个RequestContext实例(docs),就像您的登录视图一样,因此它知道哪个用户已登录(以及其他内容)。所以而不是:

def index(request):
    t = loader.get_template('reboot/index.html')
    servers = Server.objects.all()
    c = Context( {
      'servers': servers,
    })
    return HttpResponse(t.render(c))

做吧:

def index(request):
    servers = Server.objects.all()
    context = {
      'servers': servers,
    }
    return render_to_response('reboot/index.html', context, context_instance=RequestContext(request))

编辑

这不是真的render_to_response。正如导入所说,这只是一条捷径。

Django 的上下文处理器(基本上,将变量添加到模板上下文的函数)是基于请求的,因此只有在您指定 aRequestContext时才会调用,其中包括将变量包含到模板django.contrib.auth.context_processors.auth中的上下文处理器。user

相当于您的代码将是:

def index(request):
    t = loader.get_template('reboot/index.html')
    servers = Server.objects.all()
    c = RequestContext(request, {
      'servers': servers,
    })
    return HttpResponse(t.render(c))
于 2013-08-29T16:57:56.790 回答