Django updating values to OneToOneField field - python

Hi I have User object imported from auth and different model named UserProfile which has bio of user
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
bio=models.TextField(null=True,blank=True, max_length=128)
def __unicode__(self):
return self.user
as the user is OneToOneField Im having inserting data into it
q=User.objects.get(id=1)
>>> <User: test>
q.userprofile_set.create(bio='check')
Im getting error 'User' object has no attribute 'userprofile_set'. Im new to django..How should I insert data which has a OneToOneField
Any help is much appreciated...Thnaks in advance

ManyToManyFields and Foreignkey fields create a object.relation_set property on the object you can follow, but OneToOneFields do not. Instead you use object.relation directly (since we know there's only one).
So try q.userprofile.create(bio="check") instead!
(Bonus tip: Whenever you want to see the properties of a python object, use the dir() method, it will show you the full list of properties available!)

Related

How i could use the "username" from the User model as id in other model in Django?

I'm new in this and I'm trying to use in Django the username as id in other model.
I imported the base model for User in Django, but when i'm doing:
author = User().get_username()
The field doesn't appear.
Is there any method to use the "username" from the User model?
Thanks for your help and sorry for my English.
You need to use ForeignKey to relate your current model with User model to access its methods.
class MyModel(models.Model):
author = models.ForeignKey('User', on_delete=models.CASCADE)
...
Then you can call .get_username() method to retrieve username. Assuming my_obj is MyModel class object, calling my_obj.author.get_username() will do the job.

Auto pass or recieve a ForeignKey instance value

Say I have a Profile Model that gets created automatically from auth.models.User by using signals and on the Profile model OneToOneField, I have a company attribute tied to a Company model by ForeignKey. Meanwhile this Company model gets created at signup too via Foreignkey using formset_factory in views. What I am aiming to achieve is having the Company instance created at signup passed to the Profile instance Foreignkey as well. Tried using signals, overiding save methods etc. doesn't seem to be working.
Here's a sample code, all suggestions are greatly appreciated in advance.
from django.contrib.auth.models import User
class Company(models.Model):
comp_admin = model.ForeignKey(User, on_delete=models.CASCADE)
comp_name = models.CharField(max_length=200)
.............................
.............................
other attributes omitted
.............................
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
Ok, literally, few minutes after asking this question, I figured it out. What I did was use post_save to update the company attribute, but checked if the Company instance had the same comp_admin attribute value as the user attribute value. I'm guessing overriding the init method will work as well, but seems a bit long.

Why does not django delete one to one relationship?

I have the following simple relationship:
class User(models.Model):
fields here
class UserProfile(models.Model):
user = models.OneToOneField(User)
I did the following in the shell:
user = User.objects.create(...)
profile = UserProfile.objects.create(user=user)
user.userprofile
...<UserProfile: UserProfile object>
user.userprofile.delete()
...(1, {'accounts.UserProfile': 1})
user.userprofile
...<UserProfile: UserProfile object>
From the above, you can see that I create User and UserProfile instances. Than I try to delete UserProfile instance and it is deleted (at least seems like). Than I do user.userprofile and it's like it never was deleted.
After little digging into the Django delete method, I realized that when I do user.userprofile.delete() Django just deletes userprofile's pk and the rest fields are not touched. What I do not understand is what should I do in order to get the following result:
user.userprofile.delete()
user.userprofile
...RelatedObjectDoesNotExist: User has no userprofile.
Does anyone have some ideas or code snippets?
You can reload the user from the database:
user = User.objects.get(pk=user.pk)
That will refresh all its attributes including the userprofile.
You can use Model.refresh_from_db:
user.refresh_from_db
Relevant docs

Issues with OneToOne Field in Serializer in django rest framework

I have model UserProfile related with User Model via one-to-one relationship.
UserProfileSerializer is defined correctly and it serializes userprofile object well.
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, primary_key=True)
country = models.CharField(max_length=255)
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('user','country')
But it gives error {'user':['This field is required']} on passing data.
>>> s = UserProfileSerializer(data = {'user':1,'country':'YY'} )
>>> s.is_valid()
False
>>> s.errrors
{'user':['This field is required']}
This might be too late to help, and I'm not sure exactly what you're trying to do, but try setting the user field in your serializer to use a PrimaryKeyRelatedField so that you can represent a User with an ID, or set the user field to be readonly if you only want to update UserProfile things. If you don't want to use a primary key, other relationship fields are here.
If you change the user field to be a PrimaryKeyRelatedField and you want the user data to return as it is now, you might want to make two UserProfile serializers - one for write operations, and one for reading. After a create or an update, you can switch to the read serializer to populate the response.

Django: given a user object, how do I get a corresponding UserProfile object?

Have a UserProfile object that successfully extends the django default user class:
class UserProfile(models.Model):
user = models.OneToOneField(User)
and have updated the settings.py file accordingly:
AUTH_PROFILE_MODULE = 'authorization.UserProfile'
Everything works fine, just wondering: how do I get to objects associated with UserProfile for a given context within a view?
Assume that I can just get context.user if the user is logged in, but then how do I grab the corresponding UserProfile object?
In view:
request.user.get_profile().field_name
In template:
{{user.userprofile.field_name}}
You can get it like -
context.user.userprofile
Detail here.

Categories