Let's say my website will have a "reset password" button for when the user forgets his password, it will generate a link with a hash based on url_token field from Password_Reset_Token and email it to the user.
If the user access the url, the view can then reset his password and delete the Password_Reset_Token object.
But what if it expires and the link isn't accessed? Is there a way to add a daily task to clean expired objects?
Or is there a more clever way to do this?
Worth nothing that my application is entirely AJAX based and has no url redirecting
class Password_Reset_Token(models.Model):
url_token = models.AutoField(primary_key = True)
created_date = models.DateTimeField(auto_now_add=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
expiringdays = models.IntegerField(default = 12)
I would recommend creating a custom command that purges expired records. Run that periodically or via an automated process such as cron.
Related
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.
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)
I created a working "Log in with facebook" setup with django-allauth. However, I want those new user accounts that allauth creates to not be activated automatically.
Basically I want to activate all new accounts from the Django admin pages.
What would be a best practice solution to this?
Thanks
How do you know that an account is activated or not? You need some kind of field in your User model.
Let's say that your field is called is_activated:
class User(BaseUser):
is_activated = models.BooleanField(default=False)
and that's it. This field's default value will be False which means that a created user is not activated by default.
Then, you can add this field to the admin page and toggle it from there.
Hope it helps!
I'd suggest what follows because when I made cogofly I had this huge problem where some people (few but some of them do) click sometimes on "log in with google" and sometimes on "log in with facebook" and this is the same person! So be careful with that and this solution will help you to avoid such problem. The only thing to remember: there's only one primary key for all social networks: the email.
Like it's written in the documentation, I'd make a OneToOne link to the User model.
From this I would suggest this:
precise the date of the first login
precise the date of the last login
precise if the account has been validated
Like this:
from django.contrib.auth.models import User
class Person(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
is_activated = models.BooleanField(default=False)
And make a social login model where you precise how the user logged in:
class SocialLogin(BaseModel):
S_GOOGLE = 1
S_FACEBOOK = 2
TAB_S_LOGIN = {
S_GOOGLE: _("Google"),
S_FACEBOOK: _("Facebook"),
}
logged_in = models.IntegerField(
choices=[(a, b) for a, b in list(TAB_S_LOGIN.items())],
default=S_GOOGLE)
date_first_login = models.DateTimeField(auto_now_add=True,
verbose_name=_('First login'))
date_last_login = models.DateTimeField(auto_now=True,
verbose_name=_('Last login'))
person = models.OneToOneField(Person, on_delete=models.CASCADE)
def logged_in_desc(self):
return SocialLogin.TAB_S_LOGIN[self.logged_in]
def __str__(self):
return '{} / {}'.format(
self.logged_in_desc(),
description if self.description is not None else '?')
I have a model that saves a endusers progress on a task.
class TaskCompleted(models.Model):
session = models.ForeignKey('sessions.Session', on_delete=models.SET_NULL,blank=True, null=True)
user = models.ForeignKey(User, blank=True, null=True)
task = models.ForeignKey(Task, blank=True, null=True)
The enduser might be logged in or might not be. If they are logged I save the it against the user and if they are not I save it against the session.
When the a user logs in I want to find any tasks they have completed while unauthenticated and then update the user foreign key to relate it to their account.
I am finding that the session is destroyed thus setting the session to Null.
I am interested in other's suggestions on how to handle this?
The session data is not destroyed when a user is logged in - the data is saved to a new session (the key is "cycled"). You can still use request.session['mykey']. You can do a few things to persist/change the ownership of your TaskCompleted instance. One option would be to save the TaskCompleted instance id in the session for anonymous users, and override the login view to assign that instance to the user on successful login. (And if you follow this, you won't need the session = models.ForeignKey() field in your model)
[Django 1.5.1]
I've set up django-profiles and django-registration for my small site in a way that involves a 'custom' registration backend such that during registration, a new user fills out their username, password, and profile fields in one go. But I'm now trying to allow users to log in with Facebook and trying to use django-facebook. As far as I understand, logging in through django-facebook's Facebook login will authenticate someone, but that won't create a user object nor a profile object.
So the idea I had in mind would be to add an extra profile field which holds a user's potential Facebook ID(which I believe is unique) if they want to use Facebook. Then force a check on every template if the user has a profile or not, and if not, to direct them to the 'create profile' page. Then whenever a user logs in through the Facebook login, it'll somehow link their session with the corresponding profile object which matches the Facebook ID (and consequently the user object corresponding to the profile object). I think I'd have to apply a filter and then create a 'signal', but I'm not too sure how to do that.
This sounds very convoluted though. How might I be able to get this accomplished the right way?
Here's how I suggest you do things. Do away with django-facebook and look into django-allauth. It will handle accounts (registration, logic, connecting social accounts).
Also, django-profiles has many issues with 1.5+ for me and I don't bother with it and instead create my own profiles app and UserProfile model with any additional fields that wouldn't be handled by django-allauth.
An example from one of my implementations
class UserProfile(models.Model):
user = models.OneToOneField(User)
default_address = models.OneToOneField(Address, blank=True, null=True)
default_tshirt_size = models.CharField(blank=True, null=True, choices=constants.tshirt_sizes, max_length=50)
default_shoe_size = models.CharField(blank=True, null=True, choices=constants.shoe_sizes, max_length=50)
Your user profile model should be pointing to the same User model allauth is using.
from allauth.utils import get_user_model
User = get_user_model()
Here's a neat method I use to create the User's profile automatically if it hasn't been already.
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
Then just create a sign-up form class with a save() method that takes user as an argument. Link to this class in your settings file.
ACCOUNT_SIGNUP_FORM_CLASS = 'yourproject.yourapp.forms.SignupForm'
See this post on for a somewhat relevant example, except of course with your implementation you'll probably want to get the UserProfile based on the user.id at that point, and save the additional values to the profile instance.
How to customize user profile when using django-allauth