Home > Enterprise >  Django - How do I set default value to primary key
Django - How do I set default value to primary key

Time:09-13

I have made custom User model with AbstractBaseUser.

and I'm trying to make the primary key of the class to start from certain numbers as new users sign up to the site.

Such as '2022001' - '2022002' - '2022003' and so on.

I have searched on stack overflow and other sources, and some people suggest define function within the custom user's class model, but i have failed to do that.

is there a simple way to generate auto_increment number starting with the custom number from models.py ?

or Is it possible for me to give that certain number in views.py as new users sign up?.

here is my register function. from views.py

def register_user(request):
    
    
    
    
    
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            user = authenticate(username=username, password=password)
            login(request, user)
            messages.success(request, ("You have successfully registered."))
            return redirect('home')
    else:
        form = RegistrationForm()


    return render(request, 'register/register_user.html', {'form' : form})

Thank you

CodePudding user response:

user = authenticate(id=2022001 ,username=username, password=password) if you want to modify your primary key this method may help. try this.....

CodePudding user response:

add following field to your model:

id = models.BigIntegerField(primary_key=True)

now you give it what ever value you'd like

  • Related