简体   繁体   English

非管理员仪表板的Django登录页面

[英]Django Login Page for Non-admin Dashboard

I am trying to make a login page for a dashboard that users can access but they cannot access the main admin page. 我正在尝试为仪表板创建一个登录页面,用户可以访问该仪表板,但他们无法访问主管理页面。 I set the permissions up I needed and the groups. 我设置了所需的权限和组。 And I wanted to use the built in login view, but I couldn't figure out how to change the template location, so I copied the view from django/contrib/auth/views to auth_views in my own project. 而且我想使用内置的登录视图,但是无法弄清楚如何更改模板位置,因此我将视图从django / contrib / auth / views复制到了自己项目中的auth_views。 I then overwrote the template to the correct location. 然后,我将模板重写到正确的位置。 Everything is working fine at this point, I get to the login page and I type in my credentials. 此时一切正常,我进入登录页面并输入凭据。 But instead of redirecting to the dashboard I get redirected back to the login page, and form.is_valid() returns false for some reason. 但是,我没有重定向到仪表板,而是重定向回登录页面,并且由于某种原因, form.is_valid()返回false。

I also tried this by just importing django.contrib.auth.views as auth_views and moving my template to where they want it but I have the same issue. 我还通过仅将django.contrib.auth.views导入为auth_views并将模板移动到他们想要的位置来进行尝试,但是我遇到了同样的问题。

Here is my code: 这是我的代码:

urls.py: urls.py:

urlpatterns = [
    url(_(r'^dashboard/'), views.dashboard, name="dashboard"),
    url(_(r'^dashboard-login/'), auth_views.login, name="dashboard-login"), 
]

views.py: views.py:

def in_client_group(user):
    if user:
        return user.groups.filter(name='Clients').count() == 0
    return False

@user_passes_test(in_client_group, login_url='/dashboard-login/')
#@permission_required('client.is_client', login_url='/dashboard-login/')
def dashboard(request):
    current_client = request.client
    files = ClientUpload.objects.filter(client__icontains=current_client)

    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            new_file = UploadFile(file = request.FILES['file'])
            new_file.save()

        return HttpResponsePermanentRedirect('/dashboard/')
    else:
        form = UploadFileForm()

    data = {'form': form, 'client': current_client, 'files': files}
    return render_to_response('dashboard.html', data, context_instance=RequestContext(request))

dashboard_login.html: dashboard_login.html:

{% extends "base.html" %}
{% load i18n %}

{% block title %}XXXX - {% trans 'Login to Dashboard' %}{% endblock title %}

{% block extra_css %}
{% endblock extra_css %}

{% block content %}

{% block page_header %}{% endblock page_header %}

{% if form.errors %}
<p>{% blocktrans %}Your username and password didn't match. Please try again.{% endblocktrans %}</p>
{% endif %}

<form method="post" action="{% url 'dashboard-login' %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="{% trans 'Login' %}" style="margin-top: 10px; margin-right: 5px;" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
<p>isvalid={{ valid }}  user={{ user }}</p>
{% endblock %}

{% block extra_js %}
{% endblock extra_js %}

I can't figure out why the form keeps failing validation, all it should be is a login form. 我不知道为什么表单会一直失败验证,它应该是一个登录表单。 The user is not staff nor superuser, but is active. 该用户既不是职员,也不是超级用户,但处于活动状态。 What could possibly be the reason that I just keep getting redirected back to the login page? 我只是不断重定向回到登录页面的原因可能是什么? I know next is set correctly as I checked it, the username seems to be logged in as it starts off with AnonymousUser and after login and redirecting back to the login page it says the user's username, but still says form.is_valid() is false. 我知道接下来检查时设置正确,用户名似乎是从AnonymousUser开始的,并且在登录并重定向回登录页面后,它说用户的用户名,但仍然说form.is_valid()为false 。 If it is logging the user in, why isn't it letting me redirect to the dashboard, even if I try to manually enter the URL I am brought back the login page as should happen when the decorators don't pass. 如果正在登录用户,为什么不让我重定向到仪表板,即使我尝试手动输入URL,也会像没有装饰者通过时一样带回登录页面。 But the user is in the Clients group, and does have the permission clients.is_client. 但是该用户在“客户端”组中,并且确实具有“ clients.is_client”权限。 I've tried both and can't get it to work. 我已经尝试过两次,但无法正常工作。

Any ideas? 有任何想法吗?

Also how can I change the template location for the built in login view without having to copy the entire views file over and change it that way? 另外,如何更改内置登录视图的模板位置,而不必复制整个视图文件并以这种方式进行更改? It does work when I remove the decorators but that defeats the point of it all. 当我移除装饰器时,它确实起作用了,但这使这一切变得毫无意义。

Thanks for any help 谢谢你的帮助

  1. Log in user 登录用户

    login form: 登录表单:

     class AuthenticationForm(forms.Form): """ Login form """ email = forms.EmailField(label="Email") password = forms.CharField(widget=forms.PasswordInput()) 
    class Meta: fields = ['email', 'password']

    login view 登录视图

     redirect_to = 'your url' if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = authenticate(email=request.POST['email'], password=request.POST['password']) if user is not None: if user.is_active: django_login(request, user) messages.add_message(request, messages.SUCCESS, "You are now logged in!") return HttpResponseRedirect(redirect_to) ... 

Once the user is logged in, the user will be able to submit your form. 用户登录后,该用户将能够提交您的表单。

If you are using username in stead of email login, just just those values. 如果您使用用户名代替电子邮件登录,则只需输入这些值即可。

Obviously the above is kind of dirty way and you should validate all the logins etc the standard Django way. 显然,以上是一种肮脏的方式,您应该以标准Django方式验证所有登录名。 Validate the user in the form, use clean_data etc. 验证表单中的用户,使用clean_data等。

All I'm trying to say is, log in the user first before you let them do anything else. 我要说的是,先让用户登录,然后再让他们执行其他操作。

Edit: 编辑:

Try to check the permissions with something like this: 尝试使用以下方式检查权限:

The permissions may be wrong user group etc. Test it is something like this: 权限可能是错误的用户组等。请测试如下内容:

`Permission.objects.filter(
    user=request.user, codename='perm_name' ).exists()`

also make sure you import: 还请确保您导入:

from django.contrib.auth.decorators import login_required, user_passes_test, permission_required

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM