Error creating a multi-step form using Django session - django

I'm currently working on building a multi-step registration form in Django. I followed the official documentation which can be seen here. Although the forms do not show any error, the user does not get created. Is there a problem I might be overlooking?
def signup_step_one(request):
if request.user.is_authenticated:
return HttpResponseRedirect(reverse('accounts:personal-signup'))
else:
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
# collect form data in step 1
email = form.cleaned_data['email']
password = form.cleaned_data['password1']
# create a session and assign form data variables
request.session['email'] = email
request.session['password'] = password
return render(request, 'personal-signup-step-2.html', context={
'form': form,
"title": _('Create your personal account | Step 1 of 2'),
})
else:
form = CustomUserCreationForm()
return render(request, 'personal-signup-step-1.html', {
"title": _('Create your personal account | Step 1 of 2'),
'form': form,
})
def signup_step_two(request):
# create variables to hold session keys
email = request.session['email']
password = request.session['password']
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.email = email
user.set_password(password)
user.first_name(form.cleaned_data['first_name'])
user.last_name(form.cleaned_data['last_name'])
user.save()
print('user created')
return HttpResponse('New user created')
else:
form = CustomUserCreationForm()
return render(request, 'personal-signup-step-2.html', {
"title": _('Create your account | Step 2 of 2'),
'form': form,
})

I noticed that the following line in signup_step_two function will always return the message "New user created" even if form is not valid:
return HttpResponse('New user created')
Put the above line inside the if statement. Also print form.errors in else statement or inside the template to check the problem.
Ex:
if form.is_valid():
# create the user
return HttpResponse('New user created')
else:
print(form.errors)

Related

Displaying Django Models data in html file

I want to display data taken from my Django models in my html file. So in the code bellow instead of a 0 I want the donation model data. Can someone please help? Thank you! also if anyone knows a easier way please tell me. i can update my question again if anyone needs more details.
Views.py
from django.forms import ModelForm
# Create your views here.
def index(request,*args, **kwargs):
return render(request, "index.html", {} )
#login_required(login_url='/login/')
def myview(request,id):
data= userdetails.objects.get(id=id)
return render(request,'dashboard.html',{'data':data}
def register(request ):
if request.user.is_authenticated:
return redirect('/dashboard/')
else:
form = CreateUserForm()
if request.method == "POST":
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been successfully created, {username} ')
return redirect('loginpage')
context = {'form': form}
return render(request, "register.html", context )
def loginpage(request):
if request.user.is_authenticated:
return redirect('/dashboard/')
else:
if request.method == 'POST':
username = request.POST.get('username')
password =request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('/dashboard')
else:
messages.error(request, 'Username OR password is incorrect')
context = {}
return render(request, 'login.html', context)
def logoutuser(request):
logout(request)
return HttpResponseRedirect('/login/')
#login_required(login_url='/login/')
def donate(request):
if request.method == "POST":
title = request.POST['donationtitle']
phonenumber = request.POST['phonenumber']
category = request.POST['category']
quantity = request.POST['quantity']
location = request.POST['location']
description = request.POST['description']
ins = Donation(title = title, phonenumber = phonenumber, category = category, quantity = quantity, location = location, description = description, user=request.user, )
ins.save()
return render(request,'donate.html')
Error:
File "C:\Users\jbtai\coding\GoodDeedWeb\home\views.py", line 30
def register(request ):
^
You need a view that handle that:
def myview(request):
id = request.user.id
data= userderails.objects.get(id=id)
return render(request,'dashboard.html',{'data':data}
Then in your template 'dashboard.html' you could show details:
{{data.donations}}
{{data.points}}
use this url for that view instead of the old one
path('dashboard/',views.myview, name = 'dashboard' ),

How I can return the email again to the form if the login is invalid

How I can return the register information again to the register Form if the email not valid because as default if the email invalid the form are resitting
def register_view(request, *args, **kwargs):
user = request.user
if user.is_authenticated:
return HttpResponse("You are already authenticated as " + str(user.email))
context = {}
if request.POST:
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email').lower()
raw_password = form.cleaned_data.get('password1')
account = authenticate(email=email, password=raw_password)
login(request, account)
destination = kwargs.get("next")
if destination:
return redirect(destination)
return redirect('home')
else:
context['registration_form'] = form
else:
form = RegistrationForm()
context['registration_form'] = form
return render(request, 'account/my login/register.html', context)
if the form is invalid send the form back with the data in your request.
For example in your form validation else statement should be something like this:
return render(request, 'account/my login/register.html',{'form':form})
If you want to send only the email field back then clean the other fields in the form except for the email and send only the email data back.
if form.is_valid():
# form validation logic here
else:
return render(request, 'account/my login/register.html',{'form':form})

How do I Send mail on Updating user active in Django admin?

I have changed the registration process a bit as shown below. When from the admin panel when superuser checks active, the registered user() should get mail on pressing save button. How can I do that?
Views.py
def register(request):
if request.method == "POST":
form = RegistrationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
messages.success(request, "User saved")
return redirect("accounts:login")
else:
messages.error(request, "Error in form")
else:
form = RegistrationForm()
context = {"form": form}
return render(request, 'accounts/reg_form.html', context)
I achieved it through this link: Send an email if to a Django User if their active status is changed

Unable to login with signup loginuser and password?

I'm new to django. I created a signup from from which data will be saved in the database at the time of login. It shows:
Please enter a correct username and password.
Note that both fields may be case-sensitive.
views.py:
def register(request):
registered = False
if request.method == 'POST':
form = signupform(request.POST,request.FILES)
if form.is_valid():
form.save()
if 'photo' in request.FILES:
form.picture = request.FILES['photo']
form.save()
return redirect("/accounts/login")
registered = True
else:
print(form.errors)
else:
form=signupform()
return render(request,'testApp/singup.html',{'registered':
registered,'form':form})
def user_login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/home/')
else:
return HttpResponse("Your 3010 account is disabled.")
else:
print("Invalid login details: {0}, {1}".format(username,password))
return HttpResponse("Invalid login details supplied.")
else:
return render(request, 'testapp/login.html', {})
To be able to manipulate your form instance, you need to "false save" your form before you make any changes to it.
You can do this via form = form.save(commit=False), that way you create a mutable instance of your form, which you can use to save your form data later after doing other manipulations or updating.
Also, you save the form instance after you have done all the manipulations.
def register(request):
registered = False
if request.method == 'POST':
form = signupform(request.POST,request.FILES)
signup_form = form.save(commit=False)
if signup_form.is_valid():
if 'photo' in request.FILES:
signup_form.picture = request.FILES['photo']
signup_form.save()
return redirect("/accounts/login")
registered = True
else:
print(form.errors)
else:
form=signupform()
return render(request,'testApp/singup.html',{'registered':
registered,'form':form})

The view account.views.register didn't return an HttpResponse object

Good day everyone, i'm new to django, i'm working on a project were users can create accounts, i'm using the django registration model. Here's the problem,during registration, if the username the guest wants to use is taken or the passwords entered don't match, it gives this error 'The view account.views.register didn't return an HttpResponse object. It returned None instead.' instead of informing the guest about the errors.
views.py
def register(request):
if request.method == 'POST':
user_form = UserRegistrationForm(request.POST)
if user_form.is_valid():
# Create a new user object but avoid saving it yet
new_user = user_form.save(commit=False)
# # Set the chosen password
new_user.set_password(
user_form.cleaned_data['password'])
# Save the User object
new_user.save()
profile = Profile.objects.create(user=new_user)
return render(request, 'account/register_done.html', {'new_user': new_user})
else:
user_form = UserRegistrationForm()
return render(request, 'account/register.html', {'user_form': user_form})
As Selcuk suggested in the comment, add an else clause in your views as below,
from django.http import HttpResponse
def register(request):
if request.method == 'POST':
user_form = UserRegistrationForm(request.POST)
if user_form.is_valid():
# Create a new user object but avoid saving it yet
new_user = user_form.save(commit=False)
# # Set the chosen password
new_user.set_password(
user_form.cleaned_data['password'])
# Save the User object
new_user.save()
profile = Profile.objects.create(user=new_user)
return render(request, 'account/register_done.html', {'new_user': new_user})
else: # form is not valid
return HttpResponse("Form is not valid")
else:
user_form = UserRegistrationForm()
return render(request, 'account/register.html', {'user_form': user_form})