When a user clicks an account activation link, they are redirected to my activate view:
def activate(request, uidb64, token):
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = CustomUser.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.save()
login(request, user)
return redirect('/')
else:
return HttpResponse('Activation link is invalid!')
For some reason, when they are redirected with redirect('/'), they are not automatically logged in, i.e., in the index template, user.is_authenticated is False.
If anybody knows why this is, and could help me automatically log the user in after clicking the activation link, I would be very grateful for their help.
Thanks,
Jack
I have a custom login view, and all works fine when I log users in with this. Confusingly, it uses the same code as the activate view to log users in.
def custom_login(request):
if request.user.is_authenticated:
return redirect('/')
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
if user.is_active:
print(user)
login(request, user)
return redirect('/')
else:
return redirect('/login/')
else:
return redirect('/login/')
else:
form = LoginForm(label_suffix="")
return render(request, 'core/login.html', {'form': form })
The relevant parts of my SETTINGS.py are:
# Specify login url
LOGIN_URL = "/login/"
# Specify login/ logout redirect URLs
LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = "/"
Here is the CustomUser model:
class CustomUser(AbstractBaseUser):
username = models.CharField(max_length=200, unique=True, verbose_name='Username')
first_name = models.CharField(max_length=200, blank=True, null=True)
last_name = models.CharField(max_length=200, blank=True, null=True)
email = models.EmailField(max_length=255, unique=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
about = models.TextField(max_length=1000, null=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
university = models.ForeignKey(University, on_delete=models.CASCADE, blank=True,
null=True, default=None)
profile_image = models.ImageField(upload_to='profile_images/', blank=True, null=True)
objects = CustomUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
if self.is_admin:
return True
return False
def has_module_perms(self, app_label):
if self.is_admin:
return True
return False
def num_points(self):
postVotes = self.post_set.aggregate(models.Count('votes'))["votes__count"]
commentVotes = self.comment_set.aggregate(models.Count('votes'))["votes__count"]
if postVotes is None: postVotes = 0
if commentVotes is None: commentVotes = 0
return postVotes + commentVotes
def num_posts(self):
return self.post_set.count()
def num_comments(self):
return self.comment_set.count()
def latest_activities(self):
# nola = number of latest activities
nola = 10
latest_posts = Post.objects.filter(user=self).order_by('-datetime')[:nola]
latest_comments = Comment.objects.filter(user=self).order_by('-datetime')[:nola]
latest_subcomments = Subcomment.objects.filter(user=self).order_by('-datetime')[:nola]
return sorted(chain(latest_posts, latest_comments, latest_subcomments),
key=lambda e: e.datetime, reverse=True)[:nola]
def save(self, *args, **kwargs):
# delete old file when replacing by updating the file
try:
this = CustomUser.objects.get(id=self.id)
if this.profile_image != self.profile_image:
this.profile_image.delete(save=False)
print("deleting_old_image")
except:
# when new photo then we do nothing, normal case
pass
super().save(*args, **kwargs)
Related
I cannot login to any account, because I receive an error:
Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive.(for an admin user)
And
Please enter a correct email and password. Note that both fields may be case-sensitive.
That happens after I update a profile through the profile-detail page. It just throws me to the login page after I press the Update button on the profile-update page.
Here is all the related code:
models.py
class Customer(AbstractUser):
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = UserManager()
customer_id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=50, null=True, blank=True)
last_name = models.CharField(max_length=50, null=True, blank=True)
username = models.CharField(max_length=30, null=True, blank=True)
phone = models.CharField(max_length=10, default='', null=True, blank=True)
email = models.EmailField(validators=[validators.EmailValidator()], unique=True)
description = models.TextField(max_length=1000,blank=True, null=True)
gender = models.CharField('Gender', max_length=10, choices=Gender.choices,
default='Male', null=True)
featured_img = models.ImageField(verbose_name='A profile image',
upload_to='profiles',
default='products/profile_default.jpg')
password = models.CharField(max_length=100, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return f'{self.email} {self.username} {self.customer_id}'
#staticmethod
def get_customer_by_email(email):
try:
return Customer.objects.get(email=email)
except:
return False
def exists(self):
if Customer.objects.filter(email=self.email):
return True
return False
class Meta:
verbose_name = 'Customer'
verbose_name_plural = 'Customers'
# unique_together = ['email']
class Profile(models.Model):
# USERNAME_FIELD = 'email'
profile_id = models.AutoField(primary_key=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
updated = models.DateTimeField(auto_now=True, null=True)
user = models.ForeignKey(Customer, on_delete=models.CASCADE,
related_name="customer", null=True)
class Meta:
verbose_name = 'Profile'
verbose_name_plural = 'Profiles'
# unique_together = ['email']
def __str__(self):
return f' {self.profiled}'
managers.py
class UserManager(BaseUserManager):
def create_user(self, email, first_name=None, description=None, gender=None, featured_img=None, username=None, last_name=None, phone=None, password=None):
if not email:
raise ValueError("User must have an email")
if not password:
raise ValueError("User must have a password")
user = self.model(
email=self.normalize_email(email),
)
user.first_name = first_name
user.username = username
user.last_name = last_name
user.password = make_password(password) # change password to hash
user.phone = phone
user.featured_img = featured_img
user.description = description
# user.profile = profile
user.gender = gender
user.admin = False
user.staff = True
user.active = True
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
if not email:
raise ValueError("User must have an email")
if not password:
raise ValueError("User must have a password")
user = self.model(
email=self.normalize_email(email)
)
user.username = username
user.password = make_password(password) # chang password to hash
user.admin = True
user.staff = True
user.active = True
user.save(using=self._db)
return user
views.py
#csrf_exempt
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST or None)
email = request.POST['email']
if Customer.get_customer_by_email(email=email) == False:
if form.is_valid():
user = form.save(commit=False)
# account = authenticate(request,
# username=email,
# password=request.POST['password'])
user.username = user.username.lower()
user.save()
login(request, user,
backend='allauth.account.auth_backends.AuthenticationBackend')
messages.success(request, 'The account was successfully created!!!')
return redirect(reverse_lazy('products:products'))
messages.error(request, f'{form.errors}')
return redirect(reverse_lazy('user-auth:register'))
return redirect(reverse_lazy('user-auth:login'))
form = SignUpForm()
context = {'form': form, 'user': request.user}
return render(request, 'auth/register/register.html', context)
class ProfileDetailView(
DetailView):
context_object_name = 'customer'
template_name = 'auth/profile_detail.html'
def get_object(self):
profile = Profile.objects.filter(user__customer_id=self.kwargs['pk']).first()
return profile.user
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['user'] = self.request.user
return context
class UpdateProfileView(LoginRequiredMixin,
UpdateView):
template_name = 'auth/profile_update.html'
form_class = ProfileUpdateForm
context_object_name = 'customer'
def get_success_url(self):
success_url = reverse_lazy('user-auth:profile-detail',
kwargs={'pk': self.request.user.customer_id})
return success_url
#method_decorator(ensure_csrf_cookie, name='dispatch')
def post(self, request, *args, **kwargs):
profile = self.get_object()
form = ProfileUpdateForm(instance=profile)
# if request.method == 'POST':
form = ProfileUpdateForm(request.POST, request.FILES, instance=profile)
if form.is_valid():
if profile:
form.save()
messages.success(request, 'Successfully updated!')
return redirect(self.get_success_url())
messages.error(request, 'Profile does not exist!')
return redirect(reverse_lazy('user-auth:signup'))
messages.error(request, 'Invalid data!')
return render(request, self.template_name, self.get_context_data())
def get_object(self):
profile = Profile.objects.filter(user__customer_id=self.kwargs['pk']).first()
return profile.user
# def get(self, request, *args, **kwargs):
# context = {}
# context["form"] = ProfileUpdateForm(instance=self.get_object())
# context['user'] = request.user
# return render(request, self.template_name, context)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["form"] = ProfileUpdateForm(instance=self.get_object())
context['user'] = self.request.user
return context
class DeleteProfileView(LoginRequiredMixin,
DeleteView):
context_object_name = 'customer'
template_name = 'auth/profile_confirm_delete.html'
def get_success_url(self):
success_url = reverse_lazy('user-auth:profile-detail',
kwargs={'pk': self.request.user.customer_id})
return success_url
def post(self, request, *args, **kwargs):
self.request = request
if self.get_object:
messages.success(request, 'Profile deleted successfully!')
return super().delete(request, *args, **kwargs)
messages.success(request, 'Profile does not exist!')
return redirect(reverse_lazy('user-auth:signup'))
def get_object(self):
profile = Profile.objects.filter(user__customer_id=self.kwargs['pk']).first()
return profile.user
signals.py
#receiver(post_save, sender=Customer)
def create_profile(sender, instance, created, **kwargs):
user = instance
if created:
print(user)
Profile.objects.create(
user=user
)
#receiver(pre_save, sender=Customer)
def update_profile(sender, instance, **kwargs):
# print(instance)
profile = instance
if profile.customer_id is not None:
Profile.objects.update(user=profile)
#receiver(post_delete, sender=Customer)
def delete_profile(sender, instance, **kwargs):
user = instance
customer = Customer.objects.filter(email=user.email).first()
if user and customer:
# profile.delete()
customer.delete()
print('Not exists...')
forms.py
class SignUpForm(UserCreationForm):
class Meta:
model = Customer
fields = ('username','phone', 'first_name', 'last_name', 'email', 'featured_img')
# def __init__(self, *args, **kwargs):
# super(SignUpForm, self).__init__(*args, **kwargs)
# for name, field in self.fields.items():
# field.widget.attrs.update({'class': 'input'})
class ProfileUpdateForm(forms.ModelForm):
password1 = forms.CharField(
label="Password",
strip=False,
widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
help_text=password_validation.password_validators_help_text_html(),
required=False
)
password2 = forms.CharField(
label="Password confirmation",
widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
strip=False,
help_text="Enter the same password as before, for verification.",
required=False
)
class Meta:
model = Customer
fields = ('username', 'phone', 'first_name', 'last_name', 'email', 'featured_img', 'description', 'gender')
def save(self, commit=True):
customer = super().save(commit=False)
email = self.cleaned_data.get('email')
customer.email = email.lower()
# customer.password = customer.set_password(self.cleaned_data['password1'])
if commit:
if customer.exists():
super(ProfileUpdateForm, self).save()
return customer
urls.py
from django.contrib.auth import views as auth_views
app_name = 'user-auth'
urlpatterns = [
path('register/', views.signup, name='register'),
path('accounts/login/', auth_views.LoginView.as_view(
template_name='auth/login/login.html',
success_url='products/'),
name='login'
),
path('accounts/logout/', auth_views.LogoutView.as_view(), name='logout'),
path('profile-detail/<int:pk>/', views.ProfileDetailView.as_view(), name='profile-detail'),
path('profile-update/<int:pk>/', views.UpdateProfileView.as_view(),
name='profile-update'),
path('profile-delete/<int:pk>/', views.DeleteProfileView.as_view(),
name='profile-delete'),
]
I have tried to delete my database and fill it in once again. Then I tried to find out why the email or password dis incorrect. Maybe they are wrong in the database. But I have no idea what's going on.
I am trying to create a search form, Where admin can search users and then deactivate their profiles, if it is the right account.
tried function based views and then class based views. It shows the profile in function based views but doesn't update it. and in class based view it wouldn't even show the profile.
models.py
class User(AbstractBaseUser):
objects = UserManager()
email = models.EmailField(verbose_name='email address', max_length=255, unique=True,)
type = models.CharField(max_length = 50, choices = type_choices)
name = models.CharField(max_length = 100)
department = models.CharField(max_length = 100, null = True, blank = True, choices = department_choices)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False) # a superuser
admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['type']
forms.py
class SearchForm(forms.Form):
email = forms.EmailField(required=True)
views.py
#method_decorator(login_required, name='dispatch')
class adminDeleteProfileView(LoginRequiredMixin, View):
def render(self, request):
return render(request, 'admin/view_account.html', {'form': self.form})
def form_valid(self, form):
self.form = SearchForm(request.POST)
print('im here', form.cleaned_data.get('email'))
User.objects.filter(email = form.cleaned_data.get('email')).update(active = False)
#print('Donot come here')
def get(self, request):
self.form = SearchForm()
return self.render(request)
#login_required
def admin_deactivate_profile_view(request):
error_text = ''
if request.method == 'POST':
print('here')
user_email = request.POST.get('email')
try:
print('Deactivating',user_email, 'Account.')
profile = User.objects.filter(email = user_email).first()
if request.POST.get('delete'):
User.objects.filter(email = user_email).update(active = False)
messages.success(self.request, 'Profile Updated!')
except Exception as e:
print(e)
messages.success(self.request, 'There was an error!')
return render(request, "admin/delete_profile.html", {'profile':profile})
simple query .
user=User.objects.get(email="user#email.com")
user.activate=false
user.save()
I have written a custom form for the creation of a user.
The login works for the users created on the terminal with "python manage.py createsuperuser", but it doesn't work for the users created on the website. I have checked, and the creation form works; I mean, the user is created.
This is the form
class CustomUserCreationForm(UserCreationForm):
"""
A form that creates a user, with no privileges, from the given email and password.
"""
def __init__(self, *args, **kwargs):
super(CustomUserCreationForm, self).__init__(*args, **kwargs)
class Meta:
model = CustomUser
fields = ("email",)
The model
class CustomUser(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=254, unique=True, null=True)
first_name = models.CharField(max_length=254, blank=True)
second_name = models.CharField(max_length=254, blank=True)
email = models.EmailField(blank=True, unique=True)
address1 = models.CharField(max_length=254, blank=True)
address2 = models.CharField(max_length=254, blank=True)
area_code = models.CharField(max_length=20, blank=True)
country_code = models.CharField(max_length=10, blank=True)
date_joined = models.DateTimeField(_('date joined'), default=datetime.now())
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'address1', 'address2', 'area_code', 'country_code']
objects = CustomUserManager()
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_absolute_url(self):
return "/users/%s" % urlquote(self.email)
def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
return full_name.strip()
def get_short_name(self):
"""
Returns the first name for the user.
"""
return self.first_name
def email_user(self, subject, message, from_email=None):
"""
Sends an email to this user.
"""
send_email(subject, message, from_email, [self.email])
The register view
def register(request):
registered = False
if request.method == 'POST':
user_form = CustomUserCreationForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
registered = True
else:
print user_form.errors
else:
user_form = CustomUserCreationForm()
return render(request, 'register.html', {'user_form': user_form, 'registered': registered})
The login view
def login(request):
if request.method == 'POST':
login_form = CustomUserLoginForm(data=request.POST)
username = request.POST.get('username')
password = request.POST.get('password')
user = auth.authenticate(username=username, password=password)
if user:
if user.is_active:
auth.login(request, user)
return HttpResponseRedirect('/')
else:
return HttpResponse("Your account is disabled.")
else:
print "Invalid login details: {0}, {1}".format(username, password)
return HttpResponse("Invalid login details supplied. Get back to the homepage.")
else:
login_form = CustomUserLoginForm()
return render(request, 'login.html', {'login_form': login_form})
What am I missing here?
Thanks!
First fix the class:
class CustomUser(AbstractUser, PermissionsMixin):
AbstractUser is a real User Model, the BaseUser is just the meta class.
To create a new user you should use this line, in the form or in the register view:
User.objects.create_user(username=username,email=email,password=password)
Note that set_password is used to change the password, and it logs out this user after the password changes.
For almost three days I was trying to overcome same issue. I even wrote AUTHENTICATION_BACKEND. Only after that, a message was displayed on the form that the user is not active. When in save method I assigned True to user.is_active
def save(self):
user = super().save(commit=False)
user.is_active = True
user.save()
This worked for me. I hope it will work for you as well. (Note: I was not aware of rules and posted same message for similar questions to help others as well, when get notice not to do it. If anyone will see my answer for other questions please ignore it. The above answer is edited one and mostly related to this exact issue)
We have built our platform using django and created a custom user model for our usage.
Up until now our platform was invite only and now we want to open the invites to everyone.
I've modified our custom form and view for the user registration and everything is working, but we're facing one issue. When sending an invite if the user's email is not registered on our platform we create a new user for him and set a boolean to mark him as not active. When coming in with the invite everything works OK, but if the user goes directly to our page and opens the registration form we get the error that a user with this email already exists.
We're extending the CreateView and the UserCreationForm to implement our custom registration form, so I'm guessing I must override one of the methods in these classes but not quite sure which one, I've tried with the save method of the UserCreationForm but it doesn't seem to work, it pops up the error messages without going into that method.
Any ideas on how I could do this? The implementation required would be that we look if a user with that email exists and he is inactive then save the registration form elements and set him to active, otherwise just show the error message.
class CustomUserCreationForm(UserCreationForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
super(CustomUserCreationForm, self).__init__(*args,**kwargs)
self.fields.pop('username')
class Meta:
model = DealCircleUser
#fields = ('email', 'dob', 'first_name', 'last_name')
fields = ('email', 'first_name', 'last_name')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError ("Passwords don't match")
return password2
def save(self, commit=True):
exits = DealCircleUser.objects.filter(email=self.cleaned_data["email"]).exists()
if exits:
print('We have the user')
user = DealCircleUser.objects.get(email=self.cleaned_data["email"])
else:
print('No user found')
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
#check if there is a user already created with this
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
And the view is:
class RegisterUserView(CreateView):
model = DealCircleUser
template_name = 'register.html'
form_class = CustomUserCreationForm
success_url = reverse_lazy('frontend_profile')
invitation = None
def get_form(self, form_class):
code = self.request.GET.get('code')
if code:
self.invitation = Invitation.validate_code(code)
if not self.request.user.is_anonymous():
form_class = InputEmailForm
self.object = self.request.user
form = super(RegisterUserView, self).get_form(form_class)
form.fields['email'].widget.attrs['class'] = 'form-control'
if self.request.user.is_anonymous():
if self.invitation and self.invitation.email:
form.fields['email'].widget.attrs['readonly'] = True
form.fields['first_name'].widget.attrs['class'] = 'form-control'
form.fields['last_name'].widget.attrs['class'] = 'form-control'
form.fields['password1'].widget.attrs['class'] = 'form-control'
form.fields['password2'].widget.attrs['class'] = 'form-control'
if self.invitation:
form.initial['email'] = self.invitation.email
return form
def get_context_data(self, **kwargs):
ret = super(RegisterUserView, self).get_context_data(**kwargs)
ret['twitterEnabled'] = settings.ENABLE_TWITTER
if self.request.user.is_anonymous():
#if not self.invitation or self.invitation.is_used():
# ret['invalid_code'] = True
# return ret
if self.invitation and self.invitation.is_used():
ret['invalid_code'] = True
return ret
ret['code'] = self.request.GET.get('code')
return ret
def form_valid(self, form):
ret = super(RegisterUserView, self).form_valid(form)
if type(ret) == HttpResponseRedirect:
if self.invitation:
self.invitation.status = Invitation.STATUS_REGISTERED
self.invitation.save()
messages.add_message(self.request, messages.SUCCESS,
_('Your account has been created. Welcome to DealCircle!'))
else:
messages.add_message(self.request, messages.SUCCESS, _('Your account has been updated successfully.'))
user = authenticate(email=form.cleaned_data.get('email'), password=form.cleaned_data.get('password1'))
if user and user.is_active:
login(self.request, user)
return ret
def get_success_url(self):
if self.invitation and self.invitation.deal:
return reverse('frontend_invitation_response', args=(self.invitation.code,))
else:
return reverse('frontend_profile')
def linkedin_info(user):
import oauth2 as oauth
consumer = oauth.Consumer(settings.SOCIAL_AUTH_LINKEDIN_KEY, settings.SOCIAL_AUTH_LINKEDIN_SECRET)
access_token = oauth.Token(key=user.linkedin_token, secret=user.linkedin_token_secret)
client = oauth.Client(consumer, access_token)
resp, content = client.request("http://api.linkedin.com/v1/people/~:(first-name,last-name,phone-numbers,picture-urls::(original))?format=json", "GET", "")
return resp, content
The custom user manager is this:
class DealCircleUserManager(BaseUserManager):
def create_user(self, email=None, password=None, **extra_fields):
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = UserManager.normalize_email(email)
user = self.model(email=email,
is_staff=False, is_active=True, is_superuser=False,
last_login=now, date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
from postman.models import AddressBook
AddressBook.objects.get_or_create(user=user)
return user
def create_superuser(self, email, password, **extra_fields):
u = self.create_user(email, password, **extra_fields)
u.is_staff = True
u.is_active = True
u.is_superuser = True
u.save(using=self._db)
from postman.models import AddressBook
AddressBook.objects.get_or_create(user=u)
return u
And the model is this:
class DealCircleUser(AbstractBaseUser, PermissionsMixin):
USERNAME_FIELD = 'email'
AVATAR_STORAGE_URL = 'https://%s.s3.amazonaws.com/%s'
avatar = models.ImageField(storage=s3, upload_to="users", null=True, blank=True)
avatar_thumb = ImageSpecField(cachefile_storage=s3, source='avatar',
processors=[ResizeToFill(*settings.THUMB_AVATAR)],
format='JPEG',
options={'quality': 60})
avatar_square_thumb = ImageSpecField(cachefile_storage=s3, source='avatar',
processors=[SmartResize(*settings.THUMB_AVATAR_SQUARE)],
format='JPEG',
options={'quality': 60})
email = models.EmailField(max_length=254, unique=True)
address = models.CharField(max_length=254, blank=True)
postal_code = models.CharField(max_length=100, blank=True)
city = models.CharField(max_length=254, blank=True)
country = models.ForeignKey(Country, verbose_name='country', null=True, blank=True)
phone = models.CharField(max_length=30, blank=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
dob = models.DateField(null=True, blank=True)
bio = models.TextField(blank=True)
twitter_token = models.CharField(max_length=100, null=True, blank=True)
twitter_token_secret = models.CharField(max_length=100, null=True, blank=True)
linkedin_token = models.CharField(max_length=100, null=True, blank=True)
linkedin_token_secret = models.CharField(max_length=100, null=True, blank=True)
linkedin_connection_hash = models.CharField(max_length=64, blank=True)
google_access_token = jsonfield.JSONField(null=True, blank=True)
google_user_extras = jsonfield.JSONField(null=True, blank=True)
company = models.ForeignKey(Company, verbose_name='company', blank=True, null=True)
date_joined = models.DateField(null=True)
first_visit = models.BooleanField(default=True)
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin '
'site.'))
is_active = models.BooleanField(_('active'), default=True,
help_text=_('Designates whether this user should be treated as '
'active. Unselect this instead of deleting accounts.'))
objects = DealCircleUserManager()
def get_avatar_from_url(self, url):
try:
self.avatar.save(os.path.basename(url), ContentFile(urllib2.urlopen(url).read()))
self.save()
return True
except Exception, e:
return False
def get_avatar_url(self):
return self.AVATAR_STORAGE_URL % (settings.BOTO_S3_BUCKET, self.avatar)
def get_full_name(self):
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
return self.first_name
def get_dealinvestor(self, deal):
return self.dealinvestor_set.get(deal=deal)
def is_email_valid(self):
try:
validate_email(self.email)
return True
except:
return False
def disable_first_visit(self):
self.first_visit = False
self.save()
I think that your form does not validate :
you should take a look at the clean method(s) of the UserCreationForm and then do something like this (didn't tested) :
def clean_email(self):
"""
First checking if the there is an invited user (User with same email exists and active==False ), if so validate the email.
If the user exists and is active that means that the email is already in use, we raise a ValidationError
If none of the above are True, the user does not exists at all, we should create it.
"""
email = self.cleaned_data['email']
if DealCircleUser.objects.filter(email=self.cleaned_data["email"], active=False).exists():
return email
elif DealCircleUser.objects.filter(email=self.cleaned_data["email"], active=True).exists():
raise forms.ValidationError(u'Email "%s" is already in use.' % email)
return email
I am using Django 1.5. I am a custom User model like this:
class User(AbstractBaseUser):
#id = models.IntegerField(primary_key=True)
#identifier = models.CharField(max_length=40, unique=True, db_index=True)
username = models.CharField(max_length=90, unique=True, db_index=True)
create_time = models.DateTimeField(null=True, blank=True)
update_time = models.DateTimeField(null=True, blank=True)
email = models.CharField(max_length=225)
#password = models.CharField(max_length=120)
external = models.IntegerField(null=True, blank=True)
deleted = models.IntegerField(null=True, blank=True)
purged = models.IntegerField(null=True, blank=True)
form_values_id = models.IntegerField(null=True, blank=True)
disk_usage = models.DecimalField(null=True, max_digits=16, decimal_places=0, blank=True)
objects = UserManager()
USERNAME_FIELD = 'email'
class Meta:
db_table = u'galaxy_user'
I have a custom authentication:
class AuthBackend:
def authenticate(self, username=None, password=None):
if '#' in username:
kwargs = {'email': username}
else:
kwargs = {'username': username}
try:
user = User.objects.get(**kwargs)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
Even after entering the correct username and password check_password() always returning false so that I can't login. I tried that in terminal too:
user.check_password(password)
is always returning False.
#views.py:
def login_backend(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
state = "Username or Password Incorrect!"
if user is not None:
login(request, user)
return HttpResponseRedirect('/overview/')
else:
return render_to_response('login_backend.html', {'state':state}, context_instance=RequestContext(request))
else:
return render_to_response('login_backend.html', context_instance=RequestContext(request))
The problem is that when you create your CustomUser, you save the password in open-way(without hashing). Can you give me your RegistrationForm code?
In my case:
# forms/register.py
class RegistrationForm(forms.ModelForm):
"""
Form for registering a new account.
"""
class Meta:
model = CustomUser
fields = ['username', 'password', 'email']
Register-handler:
# views.py
def register(request):
"""
User registration view.
"""
if request.method == 'POST':
form = RegistrationForm(data=request.POST)
if form.is_valid():
user = form.save() # Save your password as a simple String
return redirect('/')
else:
form = RegistrationForm()
return render(request, 'news/register.html', {'form': form})
So when you try to login:
if user.check_password(password):
return user
check_password always returns False.
Solution:
To set password properly, you should redefine save() method in RegistrationForm:
# forms/register.py
class RegistrationForm(forms.ModelForm):
"""
Form for registering a new account.
"""
class Meta:
model = CustomUser
fields = ['username', 'password', 'email']
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.set_password(user.password) # set password properly before commit
if commit:
user.save()
return user
Or simply change handler:
def register(request):
"""
User registration view.
"""
if request.method == 'POST':
form = RegistrationForm(data=request.POST)
if form.is_valid():
user = form.save(commit=False)
user.set_password(request.POST["password"])
user.save()
return redirect('/')
else:
form = RegistrationForm()
return render(request, 'news/register.html', {'form': form})