限制django中的用户注册量

Limit the amount of user registration in django

我是 django 的新手,我有一个问题。我的系统是用 django 开发的,只需要注册注册页面中给定的用户数量。如何验证和限制注册用户的数量?

系统有2个页面,基本上:在一个页面上,用户输入系统可以注册的最大用户数。在另一个页面上,用户已注册,具有上一页给出的限制。

存储最大值的数据库字段为CadastroCliente.qtde_usuarios

关注我的观点:

from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
from django.utils.decorators import method_decorator

from apps.criarusuario.forms import SignUpForm

from apps.cadastro.models import CadastroCliente # table with amount of users to be registered in the system

@login_required
def signup(request):
    form = SignUpForm(request.POST)
    count = CadastroCliente.qtde_usuarios #store the size of registered user
    if request.method == 'POST':
        if form.is_valid():
            if (CadastroCliente.qtde_usuarios == count): #verify the amout???
                form.save()
                username = form.cleaned_data.get('username')
                raw_password = form.cleaned_data.get('password1')
                user = authenticate(username=username, password=raw_password)
        else:
            if (CadastroCliente.qtde_usuarios == count): #verify the amout ??
               form = SignUpForm()
    return render(request, 'criarusuario/signup.html', {'form': form})

CadastroCliente 型号:

class CadastroCliente(models.Model):
    qtde_usuarios = models.PositiveIntegerField(verbose_name='Limit user Registration: ',
                                                validators=[MinValueValidator(1)],
                                                null=False, blank=False)

CadastroCreate的视图,在这个页面,用户设置用户注册的限制

class CadastroCreate(CreateView):
    model = CadastroCliente
    fields = [
             'qtde_usuarios'
             ]

非常感谢!

如果您想计算系统中的用户数:

CadastroCliente.objects.all().count()

它将return整数值。

主要问题之一是您试图访问 qtde_usuarios 值而不指定它存储在哪个特定实例中。这就是导致您在评论中提到的 DeferredAttribute 错误的原因:

CadastroCliente.qtde_usuarios  # this won't work
CadastroCliente.objects.first().qtde_usuarios  # this might

下一个问题是您正在使用 CreateView 来设置您的 qtde_usuarios 值。每次使用此视图时,它都会在数据库中创建一条新记录。最好保持一条记录并更新它。

你应该能够处理如下事情:

from django.contrib.auth import get_user_model
from django.views.generic.edit import UpdateView
# other imports


class SetLimitView(UpdateView):
    fields = ['qtde_usuarios']
    success_url = '/'

    def get_object(self, queryset=None):
        """Use the first object or create new."""
        return CadastroCliente.objects.first() or CadastroCliente()

@login_required
def signup(request):
    form = SignUpForm()
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user_model = get_user_model()
            qtde_usuarios = CadastroCliente.objects.first().qtde_usuarios
            if (user_model.objects.all().count() <= qtde_usuarios):
                form.save()
                username = form.cleaned_data.get('username')
                raw_password = form.cleaned_data.get('password1')
                user = authenticate(username=username, password=raw_password)
    return render(request, 'criarusuario/signup.html', {'form': form})

我只是修改你的代码以适应你的requirement.Please检查和确认

from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
from django.utils.decorators import method_decorator

from apps.criarusuario.forms import SignUpForm

from apps.cadastro.models import CadastroCliente # table with amount of users to be registered in the system

@login_required
def signup(request):
    form = SignUpForm(request.POST)
    user_Count = CadastroCliente.objects.all().count()
    count = CadastroCliente.qtde_usuarios #store the size of registered user
    if request.method == 'POST':
        if form.is_valid():
            if (CadastroCliente.qtde_usuarios == count): #verify the amout???
                form.save()
                username = form.cleaned_data.get('username')
                raw_password = form.cleaned_data.get('password1')
                user = authenticate(username=username, password=raw_password)
        else:
            if (user_Count < count): #Here you are allowing to show form if user_count is less then user limit
               form = SignUpForm()
    return render(request, 'criarusuario/signup.html', {'form': form})

谢谢

一个简单的 post_save 处理程序可能如下所示:

def user_post_save(sender, instance, created, **kwargs):
    if created and sender.objects.count() > MY_LIMIT:
        instance.is_active = False
        instance.save()

一个简单的 pre_save 处理程序如下所示:

def user_pre_save(sender, instance, **kwargs):
    if instance.id is None and sender.objects.count() > MY_LIMIT:
        instance.is_active = False  # Make sure the user isn't active