Show profile of custom user in django - python

hi i a working on a project for that i have made login and registration of a user. now i want to show full profile of user.since get_profile is not working anymore so how can i get full profile of a user
my models.py
class Consultants(models.Model):
consul_id=models.IntegerField(default=0,primary_key=True)
first_name=models.CharField(max_length=255,blank=True,null=True)
last_name=models.CharField(max_length=255,blank=True,null=True)
email=models.EmailField(max_length=255,blank=True,null=True)
username=models.CharField(max_length=255,blank=True,null=True)
password=models.CharField(max_length=50,blank=True,null=True)
last_login=models.DateTimeField(default=datetime.now,blank=True,null=True)
is_active=models.BooleanField(default=False)
def __str__(self):
return self.first_name
views.py for login and registration
def register(request):
context = RequestContext(request)
registered = False
if request.method == 'POST':
# user_form = UserForm(data=request.POST)
consultant_form = ConsultantsForm(data=request.POST)
if consultant_form.is_valid():
consultant = consultant_form.save(commit=False)
consultant.save()
registered = True
else:
print consultant_form.errors
else:
consultant_form = ConsultantsForm()
return render_to_response(
'register.html',
{'consultant_form': consultant_form, 'registered': registered},
context_instance=RequestContext(request))
def login_user(request):
context = RequestContext(request)
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
print type(username)
print "username",username
try:
user = Consultants.objects.get(Q(username= username) & Q(password= password))
print 'chala'
if user.is_active:
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, user)
return HttpResponse("welcome......you are succesfuly log in")
else:
return HttpResponse("Your UkKonnect account is disabled.")
except ObjectDoesNotExist:
return HttpResponse("INvalid User")
else:
return render_to_response('login.html', {}, context)
i want to make def full_profile and def edit_profile.
How can i get logged in user consul_id??
please help me

Not sure that I understand you problem well.. Take a look at recommended way of extending User model:
https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model
from django.contrib.auth.models import User
class Employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
department = models.CharField(max_length=100)
Then you can do:
u = User.objects.get(username='fsmith')
freds_department = u.employee.department
In your case it would be:
class Consultant(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
*your fields here*
Now you can use standard authentication forms and methods
You always can obtain consultant data as:
request.user.consultant

Related

How to connect 2 models in the admin, if they are already connected OnetoOne?

models.py
from django.contrib.auth.models import User
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True,
blank=True)
Every time for new user (when he registers and try login) I must choose user in admin ('in Customer model') see https://prnt.sc/waTmROxj3-xn for a screenshot), if I don't choose a new user I have error RelatedObjectDoesNotExist at / User has no customer(when user try to login). How to do it automatically? What I did do wrong?
It is possible to catch this exception, but then what data should be added to the customer to connect it? It won't change the user's flag to his own (https://prnt.sc/waTmROxj3-xn(screenshot)):
views.py
def cartData(request):
if request.user.is_authenticated:
try:
customer = request.user.customer
except ObjectDoesNotExist:
customer = ?
order, created =Order.objects.get_or_create(customer=customer,
complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
cookieData = cookieCart(request)
cartItems = cookieData['cartItems']
order = cookieData['order']
items = cookieData['items']
return {'cartItems': cartItems, 'order': order, 'items': items}
```
def register(request): #Register user
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
user = form.cleaned_data.get('username')
messages.success(request, f'Account created for {user} ')
return redirect('index')
def login_user(request): # Try to login
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('index')
else:
messages.info(request, "Wrong password or username.")
return redirect('login')
def processOrder(request):
transaction_id = datetime.datetime.now().timestamp()
data = json.loads(request.body)
if request.user.is_authenticated:
customer = request.user.customer
# it is possible to change the method like this: customer = Customer.objects.filter(pk=id).update(email=email, last_name=last_name, phone=phone,)
order, created = Order.objects.get_or_create(customer=customer, complete=False)
else:
customer, order = guestOrder(request, data)
if you want to extend the user model - you can:
You can extend the default User model, or substitute a completely customized model.
Create child model from user:
from django.contrib.auth.models import User
class Customer(User):
# you dont need user field any more
Create you own user:
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
# you dont need the customer any more
https://docs.djangoproject.com/en/4.1/topics/auth/customizing/
After 1 or 2 you don't need create additional user object, it should be automatically.
in your code with your models:
if request.user.is_authenticated:
try:
customer = request.user.customer
except ObjectDoesNotExist:
customer = Customer(user=request.user)
customer.save()

How to activate a user when user verify his/her phone number using Twilio in Django? If user is not verified how to deactivate a user?

How to activate a user when the user verifies his/her phone number using Twilio in Django? If the user is not verified how to deactivate a user?
Here is My code.
in forms.py file
class CreateUserForm(UserCreationForm):
email = forms.EmailField()
phone = forms.CharField(max_length=17)
country_code = forms.CharField(max_length=3, initial='+19')
class Meta:
model = User
fields = ['username', 'email', 'phone', 'password1', 'password2']
in views.py
def signupPage(request):
form = CreateUserForm()
# if request.method == 'GET':
# return render(request, 'user/signup.html')
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
# ====================================
request.session['phone'] = form.cleaned_data['phone']
request.session['country_code'] = form.cleaned_data['country_code']
authy_api.phones.verification_start(
form.cleaned_data['phone'],
form.cleaned_data['country_code'],
)
return redirect('token_validation')
# ====================================
context = {'form': form}
return render(request, 'user/signup.html', context)
in views.py
Is there any problem in token_validation function?
def token_validation(request):
if request.method == 'POST':
form = TokenForm(request.POST)
if form.is_valid():
verification = authy_api.phones.verification_check(
request.session['phone'],
request.session['country_code'],
form.cleaned_data['token']
)
if verification.ok():
request.session['is_verified'] = True
messages.info(request, 'Your Phone Number is Verified, Please Enter Your Information.')
user.is_active = True
user.save()
return redirect('verified')
else:
for error_msg in verification.errors().values():
form.add_error(None, error_msg)
else:
form = TokenForm()
return render(request,'user/token_validation.html', {'form': form})
Here I am getting an error user.is_active = True
NameError: name 'user' is not defined
when I am trying to make the user active again.
How to make the user active again when the user verifies his token.
Twilio developer evangelist here.
Each request has its own context, so in the request to token_validation your previous reference to a user no longer exists.
You should save your user ID in the session, along with the phone number and country code, then load the user from the database using that ID.

django returning 'AnonymousUser' object has no attribute '_meta' error

I am developing a feature, when a user registers it automatically logs the user in
but i get 'AnonymousUser' object has no attribute '_meta' error.
but when i use the same code to login the user it works fine.
my forms.py:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User
from .models import *
class RegisterForm(forms.Form):
fname = forms.CharField(error_messages=(), widget=forms.TextInput(attrs={"class":"fname entry", "placeholder":"First Name"}), required=True)
lname = forms.CharField(error_messages=(), widget=forms.TextInput(attrs={"class":"lname entry", "placeholder":"Last Name"}), required=True)
phone = forms.CharField(error_messages=(), widget=forms.TextInput(attrs={"class":"phone entry", "placeholder":"Phone Number"}), required=True)
password = forms.CharField(widget=forms.PasswordInput(attrs={"class":"password entry", "placeholder":"Password", "autocomplete":"off"}), required=True)
password2 = forms.CharField(widget=forms.PasswordInput(attrs={"class":"password entry", "placeholder":"Confirm Password", "autocomplete":"off"}), required=True)
def clean(self, *args, **kwargs):
fname = self.cleaned_data.get("fname")
lname = self.cleaned_data.get("lname")
phone = self.cleaned_data.get("phone")
password = self.cleaned_data.get("password")
password2 = self.cleaned_data.get("password2")
if phone and password and fname and lname and password2:
try:
user = User.objects.get(phone=PhoneNumber.objects.get(number=phone))
if user:
raise forms.ValidationError("user exists login instead")
except ObjectDoesNotExist:
pass
if password!=password2:
raise forms.ValidationError("passwords didn't match")
else:
if len(password)<8:
raise forms.ValidationError("short password! password should be longer than 8")
in my forms i have a registration form which does not inherit from django's user creation form.
my views.py:
def registerView(request):
if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
fname = form.cleaned_data.get("fname")
lname = form.cleaned_data.get("lname")
username = generate_username(fname, lname)
phone = form.cleaned_data.get("phone")
u = User.objects.create_user(email="", first_name=fname, last_name=lname, username=username, is_active=False)
u.set_password(form.cleaned_data.get("password"))
u.save()
p = PhoneNumber(user=u, number=phone)
p.save()
phone = PhoneNumber.objects.get(number=phone)
u = User.objects.get(phone=phone)
userLogin = authenticate(username=username, password=u.password)
login(request, userLogin)
return redirect('home')
else:
form = RegisterForm()
return render(request, 'main/register.html', {'form':form})
my loginView:
def loginView(request):
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
phone = PhoneNumber.objects.get(number=form.cleaned_data.get('phone'))
u = User.objects.get(phone=phone)
user = authenticate(username=u.username, password=form.cleaned_data.get('password'))
login(request, user, backend='django.contrib.auth.backends.ModelBackend')
print('success')
return redirect('home')
else:
form = LoginForm()
return render(request, 'main/login.html', {'form':form})
i have imported everything i need. the same code works with the loginView function but it doesn't work on registerView
What should i do to fix this?
You have this line in your view:
userLogin = authenticate(username=username, password=u.password)
The point to be noted here is that u is an instance of the user model and u.password will give the hashed password while authenticate expects it to be a raw password and hence returns None. In fact you don't even need to use authenticate while registering as you already have the user instance:
def registerView(request):
if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
fname = form.cleaned_data.get("fname")
lname = form.cleaned_data.get("lname")
username = generate_username(fname, lname)
phone = form.cleaned_data.get("phone")
# removed `is_active=False` as per comment by #Nahu Gere
user = User.objects.create_user(email="", first_name=fname, last_name=lname, username=username) # better variable name
user.set_password(form.cleaned_data.get("password"))
user.save()
phone = PhoneNumber(user=user, number=phone)
phone.save()
login(request, user) # Directly use saved user instance
return redirect('home')
else:
form = RegisterForm()
return render(request, 'main/register.html', {'form':form})
I got this error because In my register view, I had this code:
user.is_active = False
user.save()
then I had so the user got logged in automatically after registering an account.
user = authenticate(username=user.username, password=raw_password)
login(request, user)
I solved it by commenting out the auto login
# user = authenticate(username=user.username, password=raw_password)
# login(request, user)

How to redirect login to different pages for different users in Django?

I am working on a project that requires multiple users. How am I supposed to send the users to different pages based on their roles? Here is the code for models and view related to login.
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
Roles = (
('sales', 'SALES'),
('operations', 'OPERATIONS'),
('cashier', 'CASHIER'),
('frontdesk', 'FRONTDESK'),
('client', 'CLIENT'),
)
class UserProfile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True)
role = models.CharField(max_length=50, choices=Roles, default='client')
def __str__(self):
return self.user.username
view for login:
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username = username , password = password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("ACCount not active!!")
else:
print("someone tried to login and falied!")
print("Username : {} and Password : {}".format(username,password))
return HttpResponse("Invalid credentials!")
else:
return render(request , 'NewApp/login.html' , {})
You can do that by checking the role value and then redirecting to appropriate view:
if user.is_active:
login(request, user)
if user.userprofile.role == 'sales':
# sales users landing page
elif user.userprofile.role == 'operations':
# operations users landing page
. . . . .
else:
return HttpResponseRedirect(reverse('index'))

How to extend default user model in django2.12

I am working on a project and i am not using the default django user model instead i am using my own custom user model. but i am experiencing a problem. For my user model i have also made my own authb.py file which i have provided below and if i am using the default django authentication then it is authenticating only my superuser and not the user that i am entering through the sign up form and i am totally stuck.
first here is my authb.py
from .models import User
class AuthB:
def authenticate(self, username=None, password=None):
try:
user = User.objects.get(username=username)
return user
except:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except:
return None
but right now i am not using this authb instead i am using default authentication.
here is my models.py for user model
class User(models.Model):
is_authenticated = True
username = models.CharField(max_length= 25)
email = models.CharField(max_length= 150)
password = models.CharField(max_length= 100)
last_login = models.DateTimeField(auto_now= True)
profilepic = models.CharField(max_length= 255, default= "")
def __str__(self):
return self.username
here is my views.py file
def signup(request):
# context = {}
# return render(request, 'sign-up.html', context)
if request.method == 'POST':
# print(request.POST)
# Get form values
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
# Check if passwords match
# Check Username
if User.objects.filter(username=username).exists():
return redirect('signup')
else:
if User.objects.filter(email=email).exists():
return redirect('signup')
else:
u = User.objects.create_user(username=username, password=password, email=email)
u.save()
return redirect('login')
else:
return render(request, 'sign-up.html')
def login(request):
# context = {}
# return render(request, 'index.html', context)
if request.method =='POST':
# print(request.POST)
email = request.POST['email']
password = request.POST['password']
u= auth.authenticate(email=email, password=password)
return redirect('index')
else:
return render(request, 'login.html')
The main problem is that simple user is not able to login in my website only admin are able to login and django i not authenticating my simple user.

Categories

Resources