【问题标题】:Check for password before accessing content in django在 django 中访问内容之前检查密码
【发布时间】:2021-12-20 19:12:56
【问题描述】:

我正在尝试构建一个用户必须输入密码才能访问网站的功能。

如果您访问此站点,它会在向您显示内容之前要求输入密码 (123): https://www.protectedtext.com/djangoproj

我想不用forms.py。

页面的 URL --> 模板 --> 询问密码 --> 如果密码匹配,则显示内容

models.py

from django.db import models

# Create your models here.

class Text(models.Model):
    text = models.TextField(blank=True)
    slug = models.SlugField(unique=True)
    password = models.CharField(max_length=50)

    def __str__(self):
        return self.slug

views.py

from django.shortcuts import render
from .models import Text
import django.contrib.auth
# Create your views here.

def textview(request, slug):
    obj= Text.objects.get(slug=slug)
    return render(request, 'text/textpage.html', {'obj' : obj})

def home(request):
    return render(request, 'text/index.html', {})

我已尝试为密码创建新模板,但仍无法获得该功能。 提前致谢

【问题讨论】:

    标签: python django django-views django-templates


    【解决方案1】:

    如果我是你(并且不想使用DRF),我会做这样的事情:

    def check_password(*args, **kwargs): # decorator function for checking password
        def wrapper(func):
            if kwargs.get('password', None) == '123':
                func() # show index, if password is corrent
            else:
                raise Exception('Access denied') # else raise the exception
        return wrapper
    
    def home(request):
        try:
            password = request.GET.get('password') # get password from given parameters
            @check_password(password)
            def show_index(): # create function, maybe better to make it out of scope
                return render(request, 'text/index.html', {})
            show_index() # call function
        except:
            print('Password was not given or it is incorrect, access denied')
            return render(request, 'text/401.html', {})
    

    【讨论】:

      猜你喜欢
      • 2020-02-23
      • 2019-02-15
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 2011-03-20
      • 1970-01-01
      • 2017-03-22
      • 1970-01-01
      相关资源
      最近更新 更多