Search code examples
pythonpython-3.xdjangosaas

Limit the amount of user registration in django


I am newbie in django a I have a question. My system, developed in django, needs to register only the amount of user given in a registration page. How I do to verificate and to limit the amount of registered user?

The system has 2 page, basically: on a page, the user inputs the maximum amount of users who can register in the system. On the other page, users are registered, with the limitation given on the previous page.

The field of dabatase that stores the maximum value is CadastroCliente.qtde_usuarios

Follow my view:

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 Model:

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

View of CadastroCreate, in this page, the user sets the limit of user registration

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

Thank you very much!


Solution

  • One of the main problems is that you are attempting to access the qtde_usuarios value without specifying which specific instance it is stored in. This is what causes the DeferredAttribute error you mentioned in the comments:

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

    The next problem is that you are using a CreateView to set your qtde_usuarios value. Every time you use this view it creates a new record in the database. It would be better to maintain a single record and update it.

    You should be able to handle things as follows:

    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})