Update django user model when it's linked to another model - django

....
from django.contrib.auth.models import User
class Person(models.Model):
user = models.OneToOneField(User)
avatar = models.ImageField(upload_to="photos/")
level = models.IntegerField(default=0)
def __unicode__(self):
return u"%s" % self.user
I'd like to add an edit-person page where the user can modify his profile if he wants to. So I created not only a form for the model Person but also another one for the django model User so that the user can modify information such as username, last_name, first_name, email etc
I'm not proud of the way I did it although it works well.
So my question is:
Is there a way that I can "explode" the django User field which is in my Person model instead of having a select list in my client side?

Related

How to create two users : Buyers/Sellers in Django

I'm working on a project on how to create Two users : buyers/Sellers for Web using Django as Backend.
I've started the app "users"
I've read the Django Documentation about CustomUserModel
But Honestly don't know where to start from.
Any Suggestions?
In my opinion, a Buyer might be a seller and a seller might be a Buyer.
There are some suggestions:
Create your own application named users (This will help you full control User object in future).
Set your AUTH_USER_MODEL settings to users.User: AUTH_USER_MODEL = 'users.User' As you defined.
Define model Seller - OneToOne -> User: This contains seller's properties, Just create when access via user.seller
Define model Buyer - OneToOne -> User: This contains buyer's properties, just create when access via user.buyer
class User(AbstractUser):
# Your user's properties
# Your user's method
#property
def buyer(self):
try:
return Buyer.objects.get(user=self)
except Buyer.DoesNotExist:
default_value_of_buyer = {}
# Or define default value at model fields
return Buyer.objects.create(user=self, **default_value_of_buyer)
#property
def seller(self):
try:
return Seller.objects.get(user=self)
except Seller.DoesNotExist:
default_value_of_seller = {}
# Or define default value at model fields
return Seller.objects.create(user=self, **default_value_of_seller)
class Buyer(models.Model):
"""
You can add this to admin page to make some actions with Buyer
"""
user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, on_delete=models.CASCADE, related_name='buyer_profile')
# Other properties of Buyer
def __str__(self):
return "%s's Buyer profile" % self.user
class Seller(models.Model):
"""
You can add this to admin page to make some actions with Seller
"""
user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, on_delete=models.CASCADE, related_name='seller_profile')
# Other properties of Seller
def __str__(self):
return "%s's Seller profile" % self.user
It is not that hard buddy look:
you create a model User
class User(models.Model):
.........
types = (('b','buyer'),('s','seller'))
user_type = models.CharField(max_length=7, choices=types)
so every field has this argument called choices, it is a tuple that has tuples in it, every sub tuple is a choice and every choice has two elements the first one is what appears in the back end and the second element is what appears in the user interface, so 'b' is what appears in the back end and 'buyer' is what the user see in the form in the web site. Tell if that didn't work for you
class Account(models.Model):
types = (
('B', 'BUYER' ),('S', 'SELLER')
)
name = models.Charfield(max_length=15)
username = models.CharField(max_length=15)
email = models.EmailField()
password = models.CharField(max_length=16)
user_type = models.CharField(max_length=12, choices=types)
TRY THIS AND THEN GO TO YOUR ADMIN PAGE AND YOU WILL UNDERSTAND EVERYTHING

Adding data to created sqlite database in Django

I have created two classes in models.py in my application.
models.py
from django.db import models
# Create your models here.
class User(models.Model):
first_name = models.CharField(max_length=264, unique=True)
last_name = models.CharField(max_length=264, unique=True)
email = models.CharField(max_length=264,unique=True)
def __str__(self):
return self.first_name
class NewUser(models.Model):
categorie = models.ForeignKey('User',on_delete=models.DO_NOTHING)
area = models.CharField(max_length=264)
def __str__(self):
return self.name
as shown in my image my (User and New users)tables are created.
data is getting added to my (User) table.
But when I try to add data to my (New users) table
I get this error
Since you don't have any custom fields in your User model, you dont need to create a seperate User class, only you have to import the built in User class.
from django.contrib.auth.models import User
class NewUser(models.Model):
categorie = models.ForeignKey('User',on_delete=models.DO_NOTHING)
area = models.CharField(max_length=264)
def __str__(self):
return self.categorie.user.username
You can still get username, first_name, last_name, email etc from the default user class. Refer: https://docs.djangoproject.com/en/3.0/ref/contrib/auth/#django.contrib.auth.models.User
Most likely you haven't migrated properly. Try:
python manage.py makemigrations
python manage.py migrate
The models show up in the admin because they are present in the apps models.py. This is not related to the database!

Django: User Profile in 1.9

RELATED: get user profile in django
The above shows how to get user profile but i read that the accepted answer method is deprecated.
How would I create/get/use user profile in django 1.9?
models.py
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.OneToOneField(User)
address = models.TextField()
......
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
The above code will create a UserProfile record whenever a new user is created on User table. Then you can access the profile details like,
address = request.user.profile.address
get_profile() method returned additional informations about User. Currently, these informations can be stored in Custom User Model or in a seperate model which is related to User Model. You can do that by simply adding one2one relation with User model to your custom User model, or by subclassing the AbstructUserBase model.
Subclassing User Model example:
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
date_of_birth = models.DateField()
...
One2One Relation with User model example:
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)

Multiple types of users

I am writing a django web app that models an application where hospital staff and patients can login. The patients, nurses, and doctors all have different permissions and the models need to store different information. I am currently trying to create a user profile model that holds all the common fields, and then create separate models for each type of employee that each have a oneToOneField(UserProfile) attribute. I was wondering how I could tell which type of user was logged in from my views.py file. For example, is it possible to do something like:
if request.user.is_patient():
show patient form
elif request.user.is_doctor:
show doctor form
Here is what I have in models.py so far:
class BaseUser(models.Model):
user = models.OneToOneField(User)
username = models.CharField(max_length=30)
firstName = models.CharField(max_length=50)
middleName = models.CharField(max_length=50)
lastName = models.CharField(max_length=50)
sex = models.CharField(max_length=10)
address = models.CharField(max_length=200)
email = models.CharField(max_length=50)
phone = models.CharField(max_length=10)
User.profile = property(lambda u: BaseUser.objects.get_or_create(user=u)[0])
class PatientUser(models.Model):
user = models.OneToOneField(BaseUser)
existingConditions = models.TextField()
prescriptions = models.TextField()
Well, since you have created a custom BaseUser model, you could set up a set of properties in that class to identify it.
This is a rough example that you could use to test in the view the nature of the user:
class BaseUser(models.Model):
def is_patient(self):
try:
self.patientuser
except PatientUser.DoesNotExist:
return False
else:
return True
def is_doctor(self):
try:
self.doctoruser
except DoctorUser.DoesNotExist:
return False
else:
return True
Then, in your view, you could simply:
if request.user.baseuser.is_doctor():
show doctor form
elif request.user.baseuser.is_patient():
show patient form
To ensure that your users have a baseuser associated, you can take a look at the post-save signal for the User model. You can check how to register actions for these signals here.
Here is a very simple example on how to do this:
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
#receiver(pre_save, sender=User)
def my_handler(sender, **kwargs):
BaseUser.objects.create(user=sender, ...)

How do I save two models related with OneToOne in Django?

Here is my code:
from django.db import models
from django.contrib.auth.models import User
class Person(models.Model):
user = models.OneToOneField(User, primary_key=True)
title = models.CharField(max_length=3, choices=PERSON_TITLE_CHOICES)
first_name = models.CharField(max_length=100)
Basically, what I want to do, is when I am registering a new user, I'd like to save a Person model, already with the relation to the User.
You have two options here. You can either register a post-save hook for User and create your Person there, or you can create them together. I do the latter. Just make sure you wrap them in a transaction so if one fails, the other does also:
with django.db.transaction.commit_on_success():
user = User(...)
user.save()
person = Person(user = user, ...)
person.save()