Django rest framework one to one relation Create serializer - python

I'm a beginner to the Django Rest Frame work. I want to create a custom user but I have a problem from a long period i try to find a solution through many forums but unfortunately i didn't succeed. hope you help me
models.py
class Account(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
image=models.ImageField(upload_to='Images/',default='Images/user.png')
date=models.DateField(auto_now=True,auto_now_add=False)
Serializers.py
class AccountCreateUpdateSerializer(serializers.ModelSerializer):
user=UserListSerializers()
image=serializers.ImageField()
class Meta:
model= Account
fields=['id','user','image']
def create(self,validated_data):
user_data=validated_data.pop('user')
account=Account.objects.create(**validated_data)
User.objects.create(account=account,**user_data)
return account
the error :
enter image description here

Your problem is here:
user_data = validated_data.pop('user')
account = Account.objects.create(**validated_data)
User.objects.create(account=account, **user_data)
You're trying to create an Account before creating a User, which won't work because an Account requires a value for user_id. If your User model had a foreign key to Account, instead of the other way around, then creating the account first would be the right way to do it.
Switching to:
user_data = validated_data.pop('user')
user = User.objects.create(**user_data)
account = Account.objects.create(user=user, **validated_data)
should fix the problem as long as your UserListSerializers() is providing the correct data to create a User instance.
Hope that helps.

Related

showing which post a user liked/saved with python django.

I have trouble to display the ''saved''/''liked'' posts of my users in django/admin. I would like to have a field in the Adminpage to show which user likes which posts. I made an Userprofile model where all extra information (besides the one on the given django admin user Profile) are stored. so here is my model View:
class UserProfile(models.Model):
user = models.OneToOneField(User, null=True)
#likes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True,default=1, related_name='likes')
likedPosts=models.ManyToManyField('self')
Field1 = models.CharField(max_length=50,default='Sunny')
Field2 = models.CharField(max_length=50,default='')
class Meta:
ordering =['-user']
#def __unicode__(self):
# return self.user.username
User.profile =property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
right now in the liked post field I have only some usernames or "User object"
I tried all kinds of combinations to get the information into the admin page but as you can see I did not make it.
I tried to change the unicode and of course the liked post line. If you need more information please tell me so. I appreciate every kind of help.
django admin isn't really meant to support many to many relationships from both directions in the django admin. However, the link below contains a workaround that I think should address your problem with a better explanation of why many-to-many relationships are only shown from one side by default.
(many-to-many in list display django).
so for everybody who wants to do something similar this worked for me:
class UserProfile(models.Model):
likedPosts = models.ManyToManyField('self',default=None,blank=True)
def __unicode__(self):
return "{0}".format(self.user.likes.all())

Foreign key use with user model upload

These are my models and one user can upload multiple videos but one video belongs only to one user. How do I use the foreign key concept over here? When I add a user, does this automatically add a username in the Video model? If not, how do I do that? I'm very new to django over here
class User(models.Model):
first_name=models.CharField(max_length=20)
last_name=models.CharField(max_length=20)
username=models.CharField(max_length=25, primary_key=True)
password=models.CharField(max_length=15)
email_id=models.CharField(max_length=30, default='NULL')
profile_pic=models.ImageField(upload_to='profilepics/%Y/%m/%d/',default='')
def __str__(self):
return self.username
class Video(models.Model):
username=models.ForeignKey(User,on_delete=models.CASCADE,default="")
video=models.FileField(upload_to='videos/%Y/%m/%d/',default='')
videotitle=models.CharField(max_length=100)
likes=models.PositiveIntegerField(default=0)
dislikes=models.PositiveIntegerField(default=0)
def __str__(self):
return self.video
Try the following
from django.db import models
from django.conf import settings
class Video(models.Model):
...
username = models.ForeignKey(settings.AUTH_USER_MODEL)
Instead of referring to User directly, you should reference the user model using django.contrib.auth.get_user_model(). This method will return the currently active User model – the custom User model if one is specified, or User otherwise.
More info can be found here: https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#referencing-the-user-model
Not, it won't do it automatically -- and how would it do that. You need to pass user. Also you definitely don't want to add a username, but a reference to a User object. This is misleading in the code as you have a "username" in the Video class, which acutally is not just a name (string), but a ForeignKey -- a reference to an object User when adding the new video. So what you need to do when adding a video is something along the lines of:
def add_new_video(username, filename, title):
owner = User.objects.get(username=username)
newvid = Video(username=owner, video=filename, videotitle=title)
newvid.save()
assuming that likes and dislikes will be added later on...

Filter user in django and add to a existing group

I am new to Django and I have failing on a task now for a while. I have searched in the Django docs and here for some questions but there nothing is working for me.
Here is my view:
def user_accept(request):
if request.method == 'POST':
username = AddUser.objects.filter(owner=request.user).get().user_request
group_name = Projects.objects.filter(user=request.user).get().group_url
group = Group.objects.get(name=group_name)
group.user_set.add(username)
delete_user = AddUser.objects.filter(user_request=username)
delete_user.delete()
Here is my model:
class AddUser(models.Model):
owner = models.ForeignKey(User)
title = models.CharField(max_length=20, default='', blank=True)
user_request = models.CharField(max_length=30, default='')
answer = models.BooleanField(default=False)
AddUser model is used for users to request access to a specific project. So when a user is requesting a project, data is saved to the AddUser model.
The user field is set to the "owner" of the project so I can filter every project with a proper owner.
If the owner decides to accept the request my user_accept view is executed. Here is the problem, when I try to add the username into the group, I get the following error:
invalid literal for int() with base 10: 'myusername'
I have tried to convert the username with int(username) and tried to get the username's user_id but nothing seems to work... I think it have something to do how I filter my objects but I don't get it.
So thanks a lot for your time, and have a happy new year!
You need the user id or the user object itself to add a user with group.user_set.add.
You can either retrieve the user object from the username, provided usernames are unique and add that:
user = User.objects.get(username=user_request)
group.user_set.add(user)
Or change your AddUser model to store the requester's id via a OneToOne field or ForeignKey instead of username.
Django default groups doesn't allow you to add username into it.
You have to add User objects.
Try
add_user_object = AddUser.objects.filter(owner=request.user).get()
group.user_set.add(add_user_object.owner)

Django reverse url to onetoonefield on success

Good day SO!
Recently I've started working on Django, got myself a situation which I can't find the right solution on the web to solve it. So I've got a little question about URL reversing on a success. Currently when an user successfully creates an account, the user gets reversed to a profile based on the user_id which just got created:
class Create(CreateView):
form_class = UserCreateForm # inherits from django's UserCreationForm
def get_success_url(self):
return reverse('users:profile', kwargs={'pk': self.object.pk})
This is working properly. Now I created a profile module with a OneToOneField
to the django.auth.models User model. When creating a new account, a signal is send to the create_profile_on_registration method.
#receiver(post_save, sender=User)
def create_profile_on_registration(sender, created, instance, **kwargs):
...
This is also working properly, a new profile is created on user account registration. Now I would like to reverse the user to the new created profile_id instead of the user_id. However, I cant figure out exactly how to get this properly to work. Can you give me a little push in the right direction on how to approach this issue? I can't match up the right google search words or find any examples which explains or shows how to achieve this properly.
Thanks in advance!
When you create a one to one field to your user model,
class Profile(models.Model):
user = models.OneToOneField(User)
you can access the user from the profile
profile.user
and you can also access the profile from the user
user.profile
In your view, self.object is the user, so self.object.profile.id will give you the profile id.

Save user specific data in Django

I am hacking Django, as I am new to it, to create a website to which user can login and can answer some questions. For logged in user I intend to store their username, question id and response to the question. However, after trying for multiple hours I have been completely unsuccessful. Below I have given snippets of Models.py and Views.py
Models.py - I am copying only UserProfile class and Userresponse class which are needed to create the User Profile and User Response table
# Model class for creating user
class UserProfile(models.Model):
user = models.OneToOneField(User)
def __str__(self):
return self.user.username
# Model class for getting user response
class UserResponse1(models.Model):
user = models.ForeignKey(UserProfile, default=0)
questoinId = models.ForeignKey(Question)
option = models.IntegerField(default=0)
```Views.py``
def response(request, question_id):
q = UserResponse1()
if request.user.is_authenticated():
q.user = request.user.username
q.questionId_id = question_id
q.option +=request.POST['choice']
q.save()
# Redisplay the question voting form.
return HttpResponseRedirect(reverse('polls:overallResults'))
However, on running above I get following error - Cannot assign "u'abc123'": "UserResponse1.user" must be a "UserProfile" instance.
abc123 is the login name of the user. I am not able to figure out the reason for this error. Any help on fixing this error so that I can write the data to UserResponse1 table, will be very helpful.
I am using Django 1.8 on Python 2.7
q.user is a foreign key to the UserProfile table, so you have to assign a user profile instance.
Since you have access to the user with request.user you can access the user profile using the one to one field.
user_profile = request.user.userprofile
q.user = user_profile

Categories