I'm trying to create a customized User class inheriting from django User. Problem is I already have some users in database which can not be deleted whatsoever and also I have another class (let's say reports) which have a foreignkey to User. My question is: Is there any way to create my new User class and keep the old data too?
thanks in advance.
You can create related model that links back to User. This is a common approach if you have different types of users, but there are also other use cases.
class SpecialUserProfile(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL)
special_feature = models.CharField(max_length=100, null=True, blank=True)
etc.
What you also need to do is create this profile, when new user is added to User. You can do this with post_save signal.
#receiver(post_save, sender=User)
def create_special_user_profile(sender, instance, created, **kwargs):
if created:
SpecialUserProfile.objects.create(user=instance)
You create profiles for existing user with a command or write and run a temporary function that does that for existing users in User.
Now you can use ORM in the sense of user.specialuserprofile.special_feature.
This way you'll keep using User model as a base, it won't mess with build-in user related functionalities, won't have think about new and old users and you can use this new model for any additional information about users.
Related
I'm at a loss... I'm just learning Django and I am really rather confused about how to make a field work the way I would like it to.
I understand that Django has a native "Groups" model. However, I am looking to build my own teams model for customization and practice.
Here is my models.py file for my Users app:
from django.db import models
from django.contrib.auth.models import User
class Team(models.Model):
members = models.ManyToManyField(User)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
admin = models.BooleanField("Admin Status")
Here's where I'm confused. I would like to be able to call the team that the user is part of directly from User.Profile. So, I want to add a field to my Profile class that will automatically populate with the team name when a user is added to a team.
A potential problem I can see is that, currently, I can assign a user to multiple teams. This doesn't bother me, perhaps I can have a Profile model field that automatically populates with a list of all the teams that the user is associated with. Regardless, I can't figure out what type of field I would need to use, or how to do this.
Does that make sense?
A potential problem I can see is that, currently, I can assign a user to multiple teams.
Indeed, you can however easily retrieve the Teams the myprofile object is a member of with:
Team.objects.filter(members__profile=myprofile)
You thus can make a property for the Profile model:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
admin = models.BooleanField("Admin Status")
#property
def teams(self):
return Team.objects.filter(
members__profile=self
)
Then you thus access the Teams of a myprofile with myprofile.teams.
So, I want to add a field to my Profile class that will automatically populate with the team name when a user is added to a team.
From my limited knowledge of database, you can add a name field to your Team model.
Keeping in mind your requirement as mentioned in question, i would suggest you to use django reverse relations to get all the teams the profile is associated with
user_teams = User.objects.get(id='user_id').profile_set.all()[0].team_set.all()
to know more about django ORM reverse relation, here is a very short article
I am using the django user model and want to create a logic that which user has been registered by which user like admin as a user can only register another employee or admin as a user.
Means an entry in the user model can be created by another user(user in the same user model) under some business logic.
I want to reference/know which user belongs to which user.and don't wanna create a new model to do this until no way left.
please help me with this.
Thank you
You can self reference the same model by using
created_by = models.ForeignKey('self', on_delete=models.CASCADE)
Specifically for my app, I have created this model in order to allow a user (the user_parent) to follow other users.
class Follow(models.Model):
user_parent = models.ForeignKey(User, unique=True, related_name="follow_set")
users_followed = models.ManyToManyField(User, related_name="follow_followed")
Whenever a user parent follows another user, the user being followed is added to the variable users_followed.
Right now I am trying to figure out how best to unfollow other users. Do I delete the user being followed from the users_followed variable or should I add another field to the model describing whether the user is still being followed or not?
Which is the most expensive action for the database to perform?
It would be the same in terms of expense, since it is a table update. So either approach should be fine
like http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/
but can anyone suggest how I can make an attribute of the child model required, if it is inheriting the User class without saving the user if the instance of the child model is not saved? eg.
class Customer(User):
organization = models.CharField(max_length=80, unique = True)
address = models.CharField(max_length=80)
.
..
objects = UserManager()
If in the admin.py, model Customer is registered, on execution, we get the user creation form, with password after saving it, we exit from the module. We are able to see that the user exists in the django Auth, even if the Customer is not yet created. How do I override the save of the User class. Also I need to create other users for the application the normal way. Please suggest
You're sure you're not adding an User, not a Customer. Here you are not transforming users into customers, just creating a new class. (I misread your post and thought you missed that ; I'll leave that here but anyways).
You probably don't want all users to be customers (For instance, you have staff).
Did you try removing the manager ?
Let me point out however that the Django developers themselves recommend using profiles not inheritance (See comments from James Benett in the blog article you linked).
I'm working on an online store in Django (just a basic shopping cart right now), and I'm planning to add functionality for users to mark items as favorite (just like in stackoverflow). Models for the cart look something like this:
class Cart(models.Model):
user = models.OneToOneField(User)
class CartItem(models.Model):
cart = models.ForeignKey(Cart)
product = models.ForeignKey(Product, verbose_name="produs")
The favorites model would be just a table with two rows: user and product.
The problem is that this would only work for registered users, as I need a user object. How can I also let unregistered users use these features, saving the data in cookies/sessions, and when and if they decides to register, moving the data to their user?
I guess one option would be some kind of generic relations, but I think that's a little to complicated. Maybe having an extra row after user that's a session object (I haven't really used sessions in django until now), and if the User is set to None, use that?
So basically, what I want to ask, is if you've had this problem before, how did you solve it, what would be the best approach?
I haven't done this before but from reading your description I would simply create a user object when someone needs to do something that requires it. You then send the user a cookie which links to this user object, so if someone comes back (without clearing their cookies) they get the same skeleton user object.
This means that you can use your current code with minimal changes and when they want to migrate to a full registered user you can just populate the skeleton user object with their details.
If you wanted to keep your DB tidy-ish you could add a task that deletes all skeleton Users that haven't been used in say the last 30 days.
Seems to me that the easiest way to do this would be to store both the user id or the session id:
class Cart(models.Model):
user = models.ForeignKey(User, null=True)
session = models.CharField(max_length=32, null=True)
Then, when a user registers, you can take their request.session.session_key and update all rows with their new user id.
Better yet, you could define a "UserProxy" model:
class Cart(models.Model):
user = models.ForeignKey(UserProxy)
class UserProxy(models.Model):
user = models.ForeignKey(User, unique=True, null=True)
session = models.CharField(max_length=32, null=True)
So then you just have to update the UserProxy table when they register, and nothing about the cart has to change.
Just save the user data the user table and don't populate then userid/password tables.
if a user registers then you just have to populate those fields.
You will have to have some "cleanup" script run periodically to clear out any users who haven't visited in some arbitrary period. I'd make this cleanup optional. and have a script that can be run serverside (or via a web admin interface) to clear out in case your client wants to do it manually.
remember to deleted all related entries as well as the user entry.
I think you were on the right track thinking about using sessions. I would store a list of Product id's in the users session and then when the user registers, create a cart as you have defined and then add the items. Check out the session docs.
You could allow people that are either not logged in or don't have an account to add items to a 'temp' cart. When the person logs in to either account or creates a new account, add those items to their 'real' cart. Then by just adding a few lines to your 'add item to cart' and login functions, you can use your existing models.