Django how to check if user is in path - django

I made an unique url and I want to check if the acutal url contains the uid so I made a if statement which is always false in my case so what can I change that it works and checks if the path contains the uid.
views.py
#login_required(login_url='home:login')
def ChangeEmailView(request, token):
packet = get_object_or_404(TempUrl, user=request.user)
token = packet.uid
if request.path == str(token):
if request.method == 'POST':
objects = User.objects.get(email = request.user.email)
form = EmailChangingForm(request.POST, instance=objects)
if form.is_valid():
form.save()
return redirect('home:profilesettings')
else:
objects = User.objects.get(email = request.user.email)
form = EmailChangingForm(request.POST, instance=objects)
packet = get_object_or_404(TempUrl, user=request.user)
token = packet.uid
else:
print('site wasnt found')
objects = User.objects.get(email = request.user.email)
form = EmailChangingForm(request.POST, instance=objects)
packet = get_object_or_404(TempUrl, user=request.user)
token = packet.uid
return redirect('home:index')
context = {'form': form, 'token': token}
return render(request, 'home/email_settings.html', context)

Given that URL bound to ChangeEmailView was set by
path('settings/email/changeemail/<str:token>', views.ChangeEmailView , name="changeemail")
then if request.path == str(token) is always False because request.path includes full URL path (i.e. /settings/email/changeemail/) not just your token.
I think you want the following
#login_required(login_url='home:login')
def ChangeEmailView(request, token):
packet = get_object_or_404(TempUrl, user=request.user)
site_token = packet.uid
if token == str(site_token):
if request.method == 'POST':
objects = User.objects.get(email = request.user.email)
form = EmailChangingForm(request.POST, instance=objects)
if form.is_valid():
form.save()
return redirect('home:profilesettings')
else:
objects = User.objects.get(email = request.user.email)
form = EmailChangingForm(request.POST, instance=objects)
packet = get_object_or_404(TempUrl, user=request.user)
token = packet.uid
else:
print('site wasnt found')
objects = User.objects.get(email = request.user.email)
form = EmailChangingForm(request.POST, instance=objects)
packet = get_object_or_404(TempUrl, user=request.user)
token = packet.uid
return redirect('home:index')
context = {'form': form, 'token': token}
return render(request, 'home/email_settings.html', context)
Django will extract last entry of URL path and pass to your view as the token parameter, you can just use that to check if your uid is present.

Related

context processor: how to write login and signup in all views

I created a view for Login/Signup/Forget Password (5 forms in single view). I need these forms in header so I added links in base.html and extended in all templates. How can I make this view available for all templates.
def master_link(request):
login_form = UserLoginForm()
send_otp_form = SendOTPForm()
verify_otp_form = VerifyOTPForm()
registration_form = RegistrationForm()
forget_password_form = ForgetPasswordForm()
if request.method == 'POST' and 'login_submit' in request.POST:
login_form = UserLoginForm(request.POST)
if login_form.is_valid():
user = login_form.login(request)
if user:
login(request, user)
return HttpResponseRedirect(reverse('home'))
elif request.method == 'POST' and 'send_otp_submit' in request.POST:
send_otp_form = SendOTPForm(request.POST)
if send_otp_form.is_valid():
mobile_number = send_otp_form.cleaned_data['mobile_number']
type_otp = send_otp_form.cleaned_data['type']
otp = random.randint(1000, 9999)
otpobj = sendotp.sendotp.sendotp(settings.AUTH_KEY, str(otp) + ' keep otp with you.')
otpobj.send(mobile_number, 'TestOTP', otp)
return HttpResponseRedirect(reverse('verify_otp', args=(mobile_number, type_otp)))
elif request.method == 'POST' and 'signup_submit' in request.POST:
registration_form = RegistrationForm(request.POST)
if registration_form.is_valid():
user = registration_form.save(commit=False)
mobile_number = registration_form.cleaned_data['mobile_number']
user.username = registration_form.cleaned_data['mobile_number']
password = registration_form.cleaned_data['password']
gender = request.POST.get('inlineRadioOptions')
user.gender = gender
user.mobile_number = mobile_number
user.set_password(password)
user.save()
new_user = authenticate(username=mobile_number, password=password)
login(request, new_user)
return HttpResponseRedirect(reverse('home'))
elif request.method == 'POST' and 'forget_password_submit' in request.POST:
forget_password_form = ForgetPasswordForm(request.POST)
if forget_password_form.is_valid():
password = forget_password_form.cleaned_data['password']
mobile_number = forget_password_form.cleaned_data['mobile_number']
user = User.objects.get(mobile_number=mobile_number)
user.set_password(password)
user.save()
return HttpResponseRedirect(reverse('home'))
elif request.method == 'POST':
verify_otp_form = VerifyOTPForm(request.POST)
if verify_otp_form.is_valid():
return HttpResponseRedirect(reverse('home'))
# SportsMaster
sports_data = SportsMaster.objects.all()
context = {
'login_form': login_form,
'send_otp_form': send_otp_form,
'verify_otp_form': verify_otp_form,
'registration_form': registration_form,
'forget_password_form': forget_password_form,
'sports_data':sports_data,
}
return render(request, 'user_front/user_login.html', context)
I can't write these functions in all views. I know I can use context processor to send variables in all templates but how can I use these functions in all views. Also I have 3 apps and I have to send these variables only in 1 app.

Django authenticate always return None even if username and password are correct

I'm trying to do a web page using django. Where a user can register and login to the page. But When I try to login the authenticate function returns None even if the entered password and username are correct.
I'm using django version 2.1.2 and Python 3.5
I have tried adding
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
in settings.py
this is the function that I'm using for registration.
def SignUp(request):
countryobj = Country.objects.all()
if request.method == 'POST':
form = CustomUserCreationForm(request.POST or None)
gr=request.POST.get('grade')
if gr == 'Grade':
messages.add_message(request, messages.WARNING, 'Select Any Grade')
return render(request, 'authentication/registration.html', {'form': form, 'countries': countryobj})
if form.is_valid():
print("hihihih")
user = form.save()
user.refresh_from_db()
username= request.POST.get('username')
user.password=form.cleaned_data.get('password1')
user.student.birthdate = form.cleaned_data.get('birthdate')
user.student.school_name = form.cleaned_data.get('school_name')
user.student.individual = form.cleaned_data.get('individual')
user.student.school_address = form.cleaned_data.get('school_address')
user.student.country = form.cleaned_data.get('country')
user.student.state = form.cleaned_data.get('state')
user.student.communication_address = form.cleaned_data.get('communication_address')
user.student.c_country = form.cleaned_data.get('c_country')
user.student.c_state = form.cleaned_data.get('c_state')
user.student.grade = form.cleaned_data.get('grade')
user.student.cost = form.cleaned_data.get('cost')
user.student.total = form.cleaned_data.get('total')
user.student.type_user = form.cleaned_data.get('type_user')
user.student.currency=form.cleaned_data.get('currency_code')
user.save()
subject = 'Registration Successfull'
message = 'You have successfully completed registration....'+'\n'+'Username:' +user.username+'\n'+ 'Password:' +user.password
email_from = settings.EMAIL_HOST_USER
recipient_list = [user.email]
send_mail(subject, message, email_from, recipient_list)
messages.add_message(request, messages.SUCCESS, 'Registration Successfull .. Check E-mail for credentials')
return redirect('login')
else:
form = CustomUserCreationForm()
return render(request, 'authentication/registration.html', {'form': form,'countries':countryobj})
else:
form = CustomUserCreationForm()
print("lalala")
# return render(request, 'authentication/registration.html')
print(countryobj)
return render(request, 'authentication/registration.html',{'form':form,'countries':countryobj})
This is the function that i use for login
class getLogin(View):
def get(self, request):
if request.user.is_authenticated:
return render(request, "authentication/signin.html")
else:
return render(request,"authentication/signin.html")
def post(self, request):
user = request.POST.get('user')
password = request.POST.get('pass')
usernamelog = User.objects.get(username=user)
auth = authenticate(username=usernamelog, password=password)
print("auth",auth)
if auth:
request.session['user']=auth.id
request.session['grade']=auth.student.grade
print("re",request.session['user'])
print("ath",auth.username)
request.session['username']=auth.username
print("usr", request.session['username'])
request.session['super']=auth.is_superuser
print("ddd",auth.student.grade)
# request.session['auth'] = auth.is_superuser
if auth.is_superuser:
return render(request,"app/admin.html")
else:
student_id=request.session['user']
grade = request.session['grade']
ex = Exam.objects.filter(level=grade)
code = Code.objects.filter(student_id=student_id)
return render(request, "app/student.html", {'link': ex, 'code': code,'profile':student_id})
else:
messages.add_message(request, messages.ERROR, 'Username or password mismatch')
return redirect('login')
I'm not able to authenticate the user even the given username and password are correct
First of all, as Daniel Roseman pointed out, you are overwriting the correctly saved user object with unhashed password. If you want to save the Student model, the you should call user.student.save() instead of user.save().
def SignUp(request):
countryobj = Country.objects.all()
if request.method == 'POST':
form = CustomUserCreationForm(request.POST or None)
gr=request.POST.get('grade')
if gr == 'Grade':
messages.add_message(request, messages.WARNING, 'Select Any Grade')
return render(request, 'authentication/registration.html', {'form': form, 'countries': countryobj})
if form.is_valid():
print("hihihih")
user = form.save()
user.student.birthdate = form.cleaned_data.get('birthdate')
user.student.school_name = form.cleaned_data.get('school_name')
user.student.individual = form.cleaned_data.get('individual')
user.student.school_address = form.cleaned_data.get('school_address')
user.student.country = form.cleaned_data.get('country')
user.student.state = form.cleaned_data.get('state')
user.student.communication_address = form.cleaned_data.get('communication_address')
user.student.c_country = form.cleaned_data.get('c_country')
user.student.c_state = form.cleaned_data.get('c_state')
user.student.grade = form.cleaned_data.get('grade')
user.student.cost = form.cleaned_data.get('cost')
user.student.total = form.cleaned_data.get('total')
user.student.type_user = form.cleaned_data.get('type_user')
user.student.currency=form.cleaned_data.get('currency_code')
user.student.save() # this will save the Student data
subject = 'Registration Successfull'
message = 'You have successfully completed registration....'+'\n'+'Username:' +user.username+'\n'+ 'Password:' +user.password
email_from = settings.EMAIL_HOST_USER
recipient_list = [user.email]
send_mail(subject, message, email_from, recipient_list)
messages.add_message(request, messages.SUCCESS, 'Registration Successfull .. Check E-mail for credentials')
return redirect('login')
else:
form = CustomUserCreationForm()
return render(request, 'authentication/registration.html', {'form': form,'countries':countryobj})
else:
form = CustomUserCreationForm()
print("lalala")
# return render(request, 'authentication/registration.html')
print(countryobj)
return render(request, 'authentication/registration.html',{'form':form,'countries':countryobj})

Django forms ChoiceField causing form validation to fail

I have the following:
desig = []
class New_user_form(UserCreationForm):
desig = forms.ChoiceField(choices=desig)
def acquire_groups(self):
g = Group.objects.all()
for k in g:
desig.append((k.name, k.name))
print(desig)
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
designation = self.cleaned_data["desig"]
print("New_user_form save : Designation :", designation)
if commit:
user.save()
g = Groups.objects.filter(name=designation)
print("acquired group", g[0].name)
user.groups.add(g)
return user
The following is my view:
def register_user(request):
if request.method == 'POST':
form = New_user_form(request.POST)
if form.is_valid():
print("Form Validated")
new_user = form.save()
HttpResponse("Success")
else:
HttpResponse("Invalid Form")
else:
form = New_user_form()
form.acquire_groups()
g = Group.objects.all()
desig = []
for k in g:
desig.append(k.name)
args = {}
args.update({'user':request.user.username,
'form':form,
'STATIC_URL':settings.STATIC_URL,
'desig': desig,})
return render_to_response('register.html', args)
I have tried to save the form many times and it always does not validate. I dont understand why the choice field fails. I am able to use the form without the choice field. But I want to use the choice field to add new users to an existing group.
I dont understand why the form is getting invalid.
EDIT: I have changed my form as follows:
class New_user_form(UserCreationForm):
email = forms.EmailField(required=True)
desig = []
def __init__(self, **kwargs):
u = UserCreationForm.__init__(self, kwargs)
try:
if kwargs['desig_group']:
print("desig_group instantiated. Found kwargs = ", kwargs['desig_group'])
else:
print("desig_group not instantiated")
except (AttributeError, KeyError) as ex:
for g in Group.objects.all():
self.desig.append((g.name, g.name))
print("desig : ", self.desig)
desig_group = forms.ModelChoiceField(queryset=Group.objects.all())
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.email = self.cleaned_data["email"]
designation = self.cleaned_data["desig_group"]
print("New_user_form save : Designation :", designation)
if commit:
user.save()
g = Groups.objects.filter(name=designation)
print("acquired group", g[0].name)
user.groups.add(g)
return user
I have changed my view now as :
def register_user(request):
if request.method == 'POST':
print("request.POST = ", request.POST)
form = New_user_form(**request.POST)
print("form bound: ", form.is_bound)
print("Form bool: ", bool(form.errors))
if form.is_valid():
print("Form Validated")
new_user = form.save()
return HttpResponse("Added new user")
else:
print("Form is invalid")
HttpResponse("Invalid form submission.")
else:
form = New_user_form()
g = Group.objects.all()
desig = []
for k in g:
desig.append(k.name)
args = {}
args.update(csrf(request))
args.update({'user':request.user.username,
'form':form,
'STATIC_URL':settings.STATIC_URL,
'desig': desig,})
return render_to_response('emp_users/register.html', args)
With this, my form is not passing validation but all the required data is arriving in POST.
I just need to know how to validate it now.
form.cleaned_data['desig_group']
returns KeyError but the POST has that value in its query dictionary
The following is my POST:
You can't set the choices after the form is initialized. Instead, just set the choices as such:
# forms.py
class New_user_form(UserCreationForm):
desig = forms.ModelChoiceField(queryset=Group.objects.all())
...
# views.py
def register_user(request):
form = New_user_form(request.POST or None)
if request.method == 'POST':
if form.is_valid():
print("Form Validated")
new_user = form.save()
args = {}
args.update({'user':request.user.username,
'form':form, 'STATIC_URL':settings.STATIC_URL,
'desig': desig,})
return render_to_response('register.html', args)

Django didn't return an HttpResponse object

I made a simple pet store app and just added search box feature and I received this error
ValueError at /pet/search/
The view mysite.pet.views.search_page didn't return an HttpResponse object.
I tried to change render_to_response into HttpResponseRedirect but still got the same error.
Linking back to my search_page function in views.
def search_page(request):
form = SearchForm()
if request.method == "POST":
f = SearchForm(request.POST)
if f.is_valid():
Pets = Pet.objects.filter(animal = f.cleaned_data["text"])
return HttpResponseRedirect("search.html",{"Pets":Pets},{"form":form})
else:
return render_to_response("search.html",{"form":form} , context_instance = RequestContext(request))
I did some research and I understand a view has to return a HttpResponse when a HttpRequest is made and render_to_response is just a shortcut.Can someone help explain why this function won't work.Thank you
You are getting this problem because you havn't written a HttpResponse object if request type is not POST
To overcome this in your view write somthing which will process if request type is not post
def search_page(request):
form = SearchForm()
if request.method == "POST":
f = SearchForm(request.POST)
if f.is_valid():
Pets = Pet.objects.filter(animal = f.cleaned_data["text"])
return HttpResponseRedirect("search.html",{"Pets":Pets},{"form":form})
return render_to_response("search.html",{"form":form} , context_instance = RequestContext(request))
Hope this will help you thanks
The error is because when the function is called the method type is not POST and it does not find the corresponding HttpResponse object.
def search_page(request):
form = SearchForm()
if request.method == "POST":
f = SearchForm(request.POST)
if f.is_valid():
Pets = Pet.objects.filter(animal = f.cleaned_data["text"])
return HttpResponseRedirect("search.html",{"Pets":Pets},{"form":form})
else:
return render_to_response("search.html",{"form":form} , context_instance = RequestContext(request))
return render_to_response("any.html",{} , context_instance = RequestContext(request))
def addsponser(request):
if request.method == 'POST':
# return HttpResponse(request,'error is here')
if (request.POST.get('firstname') and
request.POST.get('lastname') and
request.POST.get(' email') and
request.POST.get('phone_Number') and
request.POST.get('gender') and
request.POST.get('state') and
request.POST.get('adress') and
request.POST.get('postal_code') and
request.POST.get('town')
):
fname = request.POST.get('firstname')
lname = request.POST.get('lastname')
em = request.POST.get(' email')
phn = request.POST.get('phone_Number')
gnd = request.POST.get('gender')
stt = request.POST.get('state')
add = request.POST.get('adress')
pstc = request.POST.get('postal_code')
twn = request.POST.get('town')
try:
sponser = Sponsers()
sponser.firstname = fname
sponser.lastname = lname
sponser.email = em
sponser.Phone_Number = phn
sponser.gender = gnd
sponser.state = stt
sponser.adress = add
sponser.postal_code = pstc
sponser.town = twn
sponser.save()
messages.success(request, "sponser Added")
return redirect('sponsers')
except Exception:
messages.error(request, "Failed to add sponser")
return redirect('sponsers')
else:
pass
else:
return redirect('sponsers')

Why my code does not show validation form error message?

Why my code does not show validation form error message?
I try something like this:
def index(request):
if request.method == "POST":
if request.POST['form-type'] == 'contact-form':
form = AngebotForm(None, request.POST)
if form.is_valid():
form.save()
msg = 'Good!'
return render_to_response('index.html',{'msg':msg}, context_instance=RequestContext(request))
else:
form = AngebotForm()
else:
form = MessageForm(request.POST)
if form.is_valid():
form.save()
msg = 'Good!'
return render_to_response('index.html',{'msg':msg},context_instance=RequestContext(request))
else:
form = MessageForm()
return render_to_response('index.html',{'a_form':AngebotForm(), 'm_form':MessageForm()},context_instance=RequestContext(request))
What am I doing wrong?
Because in else part you are re-initializing the form which will loose the current state of form.
Just remove these lines:
else:
form = MessageForm()
In the end your view should look like this:
def index(request):
form = AngebotForm()
m_form = MessageForm()
if request.method == "POST":
if request.POST['form-type'] == 'contact-form':
form = AngebotForm(None, request.POST)
if form.is_valid():
form.save()
msg = 'Good!'
return render_to_response('index.html',{'msg':msg}, context_instance=RequestContext(request))
else:
m_form = MessageForm(request.POST)
if m_form.is_valid():
m_form.save()
msg = 'Good!'
return render_to_response('index.html',{'msg':msg},context_instance=RequestContext(request))
return render_to_response('index.html',{'a_form':form, 'm_form':m_form},context_instance=RequestContext(request))