Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Creating a function-based view Login & Signup form in one single page

I want to create a landing page similar to linkedin's where it has the signup form and the login form at the navbar. I'm currently using a single form for both the signup and login in forms.py:

forms.py

class UserRegisterForm(UserCreationForm):
firstname = forms.CharField(max_length=200, label='')
lastname = forms.CharField(max_length=200, label='')
email = forms.EmailField(label='')

class Meta:
    model = User
    fields = ['username', 'firstname', 'lastname', 'email', 'password1']

My template includes 2 {{ form }}s and each has a submit button.

Button for the sign up {{ form }}:

name='signupbtn' type='submit'

Button for the login {{ form }}:

name='loginbtn' type='submit'

Now I have trouble trying to login or authenticate the user that I created (which is the super user). My signup/login view goes as follows:

def index(request):
if request.method == 'POST':
    if 'signupbtn' in request.POST:
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Your account has been created! You may now login.')
            return redirect('index') 
    elif 'loginbtn' in request.POST:
        username = request.POST['username']
        password = request.POST['password1']
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect('home')
else:
    form = UserRegisterForm()
    return render(request, 'users/index.html', {'form': form})

Is it possible that I need to create 2 forms in my forms.py? When I try to login, it doesn't go past the form.is_valid() under elif 'loginbtn' in request.POST:. Also both forms have {% csrf_token %}.

like image 991
Jammeh Avatar asked Dec 01 '25 05:12

Jammeh


1 Answers

I got everything to work by just simply REMOVING the form.is_valid() and adjusting the view after that.

like image 77
Jammeh Avatar answered Dec 03 '25 23:12

Jammeh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!