如何制作Django视图需要用户登录?

时间:2019-08-30 08:52:13

标签: html django security authentication django-forms

我有一个带登录屏幕的Django项目;当我输入用户名和密码时,我将被定向到主页。这样很好!但是没有什么是安全的,我可以直接登录/ allstudyplans进行查看,而无需登录并查看那里的所有信息。我的问题是如何做到这一点,因此如果不先登录就无法进入/ allstudyplans?

表格

User = get_user_model()


class UserLoginForm(forms.Form):
username = forms.CharField(label='', widget=forms.TextInput(
    attrs={
        'class': 'form-control',
        'autofocus': '',
        'placeholder': 'Användarnamn',
    }
), )

password = forms.CharField(label='', widget=forms.PasswordInput(
    attrs={
        'class': 'form-control mt-1',
        'placeholder': 'Lösenord',
    }
), )

# https://docs.djangoproject.com/en/2.1/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other
def clean(self):
    cleaned_data = super().clean()
    username = cleaned_data.get('username')
    password = cleaned_data.get('password')

    if username and password:
        user = authenticate(username=username, password=password)
        if not user:
            raise forms.ValidationError(
                'Oh! I can\'t find that user - create user first!')
        elif not user.check_password(password):
            raise forms.ValidationError(
                'Oh! That password is incorrect - try again!')
        elif not user.is_active:
            raise forms.ValidationError(
                'Oh! That user is not active in the database!')

观看次数

def home(request):
next = (request.GET.get('next'))
form = UserLoginForm(request.POST or None)
if form.is_valid():
    username = form.cleaned_data.get('username')
    password = form.cleaned_data.get('password')
    user = authenticate(username=username, password=password)
    login(request, user)
    if next:
        return redirect(next)
    return redirect('/')

context = {
    'form': form,
}
  return render(request, "utility-login.html", context)

def Assignments(request):
  return render(request, 'nav-side-team.html')

def DetailAssignment(request):
obj = Assignment.objects.all()
context = {
    'object': obj
}
  return render(request, 'nav-side-project.html', context)

def studyplans(request):
  return render(request, 'allStudyplans.html')

def detailStudyplan(request):
  return render(request, 'detailStudyplan.html')

普通项目文件(不是应用程序)中的主视图也是

@login_required
def homee(request):
    return render(request, "allstudyplans.html", {})

项目中的网址:

 urlpatterns = [
  path('admin/', admin.site.urls),
  path('account/', include('accounts.urls')),
  path('', include('accounts.urls'))
 ]

应用程序中的网址:

 urlpatterns = [
   path('', views.studyplans),
   path('login', views.home),
   path('nav-side-team.html', views.Assignments),
   path('nav-side-project.html', views.DetailAssignment),
   path('allstudyplans.html', views.studyplans),
   path('detailStudyplan.html', views.detailStudyplan),
 ]

尝试过:

@login_required
def Assignments(request):
    if not request.user.is_authenticated:
        return redirect('%s?next=%s' % ('utility-login.html', request.path))
    return render(request, 'nav-side-team.html')

2 个答案:

答案 0 :(得分:0)

学习计划缺少装饰器需要登录

根据文档https://docs.djangoproject.com/en/2.2/topics/auth/default/#the-login-required-decorator,最简单的方法应该是

@login_required
def studyplans(request):
  return render(request, 'allStudyplans.html')

答案 1 :(得分:0)

另一种方法(可能与上述方法等效)是使用“ mixins”:

from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin

class MyView(LoginRequiredMixin, View):
   ...

请注意,“ mixin”类名称应在列表中的View之前出现。

(请注意,我还显示了“需要权限的混合”。)

我想这只是出于个人喜好以及与应用程序现有源代码的一致性。