How do I change the default username for satchmo registration? - python

Since it seems that users are allowed to use their usernames to login instead of only email, I want to make the user name default to the email address. How do I achieve this? I'm assuming that I have to override the model somewhere.

Its simple. While you create the User Object, why don't you refer the username to the email..
user = User.objects.create(
username = mail,
email = mail
)
this will do..

Related

Pending request on Django

I'm building a website using Django. I have the register and login sessions working, so any user can create an account and login. But now I want a situation whereby when someone creates an account, the account will be inactive and pending until the admin accepts the user. However, I haven't implemented any code that does that before and I want to know if Django has a built-in package for that. If not, how do I go about it?
If you are using a default User model of Django at time of create user, save it like these:
user = User.objects.create_user(
first_name = first_name,
last_name = last_name,
email = email,
password = password,
username = username,
is_active = False
)
user.save()
and by using filter query list all inactive users to admin.

Passing User Data to Admin Actions in Django

I am attempting to write an admin action that accesses data from selected users. i.e. user's email. However, I have only been able to access the instance/data of the user that is currently logged in.
For example, to access the emails of selected users, I have tried:
#models.py
class Account(AbstractBaseUser):
email = models.EmailField(max_length=60, unique=True)
#admin.py
from account.models import Account
for Account in queryset:
author = request.Account.email
#OR
author = Account.objects.get(email=request.email)
print(author)
and both of these will fill "author" with the email address of the admin that is trying to pull the data.
Does anyone know how I could pull data from selected accounts with an admin action?
I was really overcomplicating it. Ironically enough, I found the answer on this site called simpleisbetterthatcomplex. The proper format was
for Account in queryset:
print(Account.email)

Different login views with Custom User

My goal is to have two views for login: one with email and password, and another with username and password.
Created a custom user class named MyUser extending from AbstractBaseUser. In that user class, stablished
USERNAME_FIELD = 'email'
Django by default uses the username field for authentication purposes of a user.
When i want users to login with email, that's easy now. But how can I do to create another view that logs in with just username and password (instead of the email)?
I do this by adding another authentication backend, using AUTHENTICATION_BACKENDS. Or you can write your own Auth backend, accepting either email or username.
Here's a simple version of an email authentication backend. Note that this requires that e-mail addresses are unique in your database, and does not case fold.
class EmailAuthBackend(ModelBackend):
"""
Email Authentication Backend
Allows a user to sign in using an email/password pair rather than
a username/password pair.
"""
def authenticate(self, request, email=None, password=None, **kwargs):
""" Authenticate a user based on email address as the user name. """
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a nonexistent user (#20760).
User().set_password(password)
else:
if user.check_password(password) and self.user_can_authenticate(user):
return user

django restframework in login module authenticate() not working

email = request.data.get('email', None)
password = request.data.get('password', None)
account = authenticate(email=email, password=password)
I am using an authenticate() function but it always returns None.
Can you suggest some modifications to rectify the function.
By default django uses name to fetch/authenticate users from request. So you have to set USERNAME_FIELD = 'email' in your User model.
Check the DJango docs
A string describing the name of the field on the user model that is used as the unique identifier. This will usually be a username of some kind, but it can also be an email address, or any other unique identifier. The field must be unique (i.e., have unique=True set in its definition), unless you use a custom authentication backend that can support non-unique usernames.
Also since you are using DRF make sure the CBVs you use does not override authentication_classes.
Here is the syntax for authenticate
user = authenticate(username=username, password=password)
Here username is USERNAME_FIELD value of the user model. By default its value is 'username' so the authenticate method will automatically check for username and password combination. to change the user to be authenticated with email we have to set USERNAME_FIELD = 'email'.
user = authenticate(username=email, password=password)

Way to use email as the authentication field?

I am using django's inbuilt authentication system. Everything seems to be working fine. There are two fields that the user is requested to input at the time of signup: username and email. While logging in they are required to enter username and password.
I'd like to change this behavior so that username field is gone. I want to treat the email as the users username. So while signing in user will be required to put email / password
Is this possible while still using django's inbuilt auth system? I'm on django 1.7
Update
I had the need to add additional fields so I added the following to models.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
telephone_number = models.CharField(max_length=100)
website_url = models.CharField(max_length=100)
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
The answer is directly in django documentation, in short words you should subclass AbstractBaseUser or AbstractUser (in second case you can't totally remove username field), create your own user manager based on BaseUserManager or UserManager and customize built-in auth forms if you're using it (or any app that you're using is using it).
This is not strictly cannon, but to avoid creating a new User class or Auth backend, I tend to let users log in with both username or email.
Anyways you'll want to ensure emails are unique as django does not check this by default.
You'll then have to override the default login view to support this. You can create something along the lines of:
class EmailUsernameLoginView(View):
def post(self, request):
next = request.POST.get('next', None)
username = request.POST.get('username', None)
password = request.POST.get('password', None)
error = ''
if username and password:
try:
usr = User.objects.get(email=username)
username = usr.username
except User.DoesNotExist:
pass # If the user doesn't exist, it's an username
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect(next)
else:
error = 'Your account is not active'
else:
error = 'The username / email - password comb is wrong'
else:
error = 'Please provide a username / email and password'
ctx = {'error': error} # Fill with needed feedback
return render(request, ctx, 'registration/login.html')
This is just a draft and you should probably include a form to help with validation / cleaning

Categories

Resources