User profile info(table) with this Cpf cnpj(field (unique)) already exists - django

My View code is this:
#login_required
def DadosUserView(request):
template_name = 'users_c2p/dados.html'
usercpf = request.user.username
profile = UserProfileInfo.objects.filter(cpf_cnpj=usercpf)
contrato_dividas = Contrato.objects.filter(cpf_cnpj=usercpf)
empresa = Empresa.objects.all()
if profile:
person = get_object_or_404(UserProfileInfo, cpf_cnpj=usercpf)
profile_form = UserProfileInfoForm(request.POST or None, instance=person)
flag = 1
else:
profile_form = UserProfileInfoForm(initial={"cpf_cnpj": usercpf,
})
flag = 0
if request.method == 'POST':
profile_form = UserProfileInfoForm(data=request.POST)
print(request.method)
print(profile_form.errors)
if profile_form.is_valid():
# Create new profile
if flag == 0:
profile_form_cpf = profile_form.cleaned_data['cpf_cnpj']
print(profile_form_cpf)
if usercpf == profile_form_cpf:
profile_form.save()
log = LogUsuario.objects.create(cpf_cnpj=profile_form_cpf, movimentacao="FIRST UPDATE")
return redirect(reverse_lazy('users_c2p:dadosuser'))
else:
return profile_form.errors
#Update profile
elif flag == 1:
profile_form_cpf = profile_form.cleaned_data['cpf_cnpj']
if usercpf == profile_form_cpf:
profile_form.save()
log = LogUsuario.objects.create(cpf_cnpj=profile_form_cpf, movimentacao="UPDATE")
return redirect(reverse_lazy('users_c2p:sucesso_cadastro'))
else:
return profile_form.errors
else:
return redirect(reverse_lazy('users_c2p:dadosuser'))
context = {
"UserData" : profile,
"profile_form": profile_form,
"Contrato": contrato_dividas,
"Empresa": empresa,
#'media_url': settings.MEDIA_URL,
}
return render(request, template_name, context)
I want to user the #Update profile part..
The #Create profile is working well, but when I try to update it, it says that user already exists and do nothing.
What should I do, so it recognizes this is the idea and then update the info that I desire?

This piece of code worked out:
def DadosUserView(request):
template_name = 'users_c2p/dados.html'
usercpf = request.user.username
profile = UserProfileInfo.objects.filter(cpf_cnpj=usercpf)
contrato_dividas = Contrato.objects.filter(cpf_cnpj=usercpf)
empresa = Empresa.objects.all()
if profile:
person = get_object_or_404(UserProfileInfo, cpf_cnpj=usercpf)
profile_form = UserProfileInfoForm(request.POST or None, instance=person)
flag = 1
else:
profile_form = UserProfileInfoForm(initial={"cpf_cnpj": usercpf,
}, )
flag = 0
if request.method == 'POST':
# Create new profile
if flag == 0:
profile_form = UserProfileInfoForm(data=request.POST)
print(request.method)
if profile_form.is_valid():
profile_form_cpf = profile_form.cleaned_data['cpf_cnpj']
if usercpf == profile_form_cpf:
profile_form.save()
log = LogUsuario.objects.create(cpf_cnpj=profile_form_cpf, movimentacao="FIRST UPDATE")
return redirect(reverse_lazy('users_c2p:dadosuser'))
else:
return profile_form.errors
#Update profile
elif flag == 1:
print("chegou!")
print(profile_form.errors)
if profile_form.is_valid():
profile_form_cpf = profile_form.cleaned_data['cpf_cnpj']
if usercpf == profile_form_cpf:
profile_form.save()
log = LogUsuario.objects.create(cpf_cnpj=profile_form_cpf, movimentacao="UPDATE")
return redirect(reverse_lazy('users_c2p:sucesso_cadastro'))
else:
return profile_form.errors
else:
return redirect(reverse_lazy('users_c2p:dadosuser'))
context = {
"UserData" : profile,
"profile_form": profile_form,
"Contrato": contrato_dividas,
"Empresa": empresa,
#'media_url': settings.MEDIA_URL,
}
return render(request, template_name, context)
When I was trying to update the database and used this code:
profile_form = UserProfileInfoForm(data=request.POST)
It wouldn't work, I realized that this is when you want to create a new entry, in order to update only, I only had take the data from the form.

Related

Add customer modal and edit in one view in django

I am kinda like stuck.
I have a BankAccountCreation() and the the form is called in a modal in Django template.
I am trying to get the same for be used for editing. but when I do that my edit button returns an empty form
My view is as below
def employee_info(request, id):
if not request.user.is_authenticated:
return redirect('/')
context = {}
banks = Bank.objects.all()
employee = get_object_or_404(Employee, id = id)
bank_instance = Bank.objects.filter(employee = employee).first()
context = {}
context['employee'] = employee
context['bank'] = bank_instance
context['banks'] = banks
context['title'] = 'profile - {0}'.format(employee.get_full_name)
if request.method == 'GET':
form = BankAccountCreation()
context['form'] = form
return render(request, 'employee/employee_info.html', context)
if request.method == 'POST':
form = BankAccountCreation(data = request.POST)
if form.is_valid():
instance = form.save(commit = False)
employee_id = request.POST.get('employee')
employee_object = employee
instance.employee = employee_object
instance.name = request.POST.get('name')
instance.branch = request.POST.get('branch')
instance.account = request.POST.get('account')
instance.code = request.POST.get('code')
instance.save()
messages.success(request, 'Bank Details Successfully Created for {0}'.format(employee_object.get_full_name), extra_tags = 'alert alert-success alert-dismissible show')
return redirect('employee_info', id=employee.id)
else:
context['form'] = form
messages.error(request, 'Error Updating details for {0}'.format(employee_object.get_full_name), extra_tags = 'alert alert-warning alert-dismissible show')
return redirect('employee_info', id=employee.id)
form = BankAccountCreation()
return render(request, 'employee/employee_info.html', context)
The Bank model has a foreign key to the Employee model

Django: change TextField before save

This is my model :
class Card(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
imp_id = models.TextField(null = True)
And here is my view :
def Add(request):
if request.method == 'POST':
form = Add_card(request.POST)
if form.is_valid():
save = form.save(commit = False)
save.user = request.user
save.imp_id = "asd" # I tried to change it here but I failed
save.save()
else:
form = Add_card()
cards = Card.objects.all()
return render(request, 'addcard.html', {'form': form, 'cards' : cards})
How can I change that textfield before save?
you can do it like this
def Add(request):
if request.method == 'POST':
request.POST.imp_id="asd"
form = Add_card(request.POST)
if form.is_valid():
save = form.save(commit = False)
save.user = request.user
save.save()
else:
form = Add_card()
cards = Card.objects.all()
return render(request, 'addcard.html', {'form': form, 'cards' : cards})
The problem could be solved by using default='asd'.

Django how to check if user is in path

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.

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