I have a model like below:
class StaffProfile(models.Model):
user = models.ForeignKey(User)
maas = models.FloatField()
maas_gunu = models.CharField(max_length=5)
When I try to insert data with a code like below:
staffprofilesay = StaffProfile.objects.filter(user = user_id).count()
if staffprofilesay > 0:
staffprofile = StaffProfile.objects.get(user = user_id)
else:
staffprofile = StaffProfile()
staffprofile.user = user_id
staffprofile.maas = calisan_formu.cleaned_data["maas"]
staffprofile.maas_gunu = calisan_formu.cleaned_data["maas_gunu"]
staffprofile.save()
I get an error like this:
Cannot assign "u'1'": "StaffProfile.user" must be a "User" instance.
What am I supposed to do?
PS: I'm using Django's User model
You need to assign a User object e.g.
from django.contrib.auth.models import User
user = User.objects.get(id=user_id)
staffprofile.user = user
user needs to be an instance of the User model, not a unicode object (which is what you are passing it).
Yes you have to pass User instance in staffprofile.user = user_id user id place.
As #david-s pointed out in a comment, if you don't have a user instance, you have to fetch from DB with an additional query.
Instead you can directly do is
staffprofile.user_id = user_id because Django behind the scene append _id in table for foreign keys so staffprofile.user will end staffprofile.user_id
Related
I am trying to create a social media type site that will allow a user to follow and unfollow another user. followers has a ManyToManyField because a user can have many followers.
models.py
class Follower(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
followers = models.ManyToManyField(User, related_name="followers")
views.py
def username(request, user):
#get user
user = get_object_or_404(User.objects, username=user)
posts = Post.objects.filter(user=user).order_by('-date_and_time')
#follow button code
follow_or_unfollow = ''
try:
following = get_object_or_404(Follower, Q(
user=user) & Q(followers=request.user))
print(following)
except:
following = False
if following:
follow_or_unfollow = True
else:
follow_or_unfollow = False
if request.POST.get('follow'):
follower = Follower.objects.create(user=request.user)
follower.followers.add(*user)
follow_or_unfollow = False
elif request.POST.get('unfollow'):
follow_or_unfollow = True
#following.delete()
When it gets the 'follow' POST request, I want it to add the user who sent it (the one that is logged in) to be added to the followers. Right now, I am getting this error when I try to do that.
TypeError: django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager.add() argument after * must be an iterable, not User
I know it says that it has to be iterable, but is there any way to just add one object at a time. Also, how would you delete this particular object?
The * in the arguments converts a list to individual args. For example-
lst = [1,2,3,4,5]
function(*lst)
can be just read as
function(1,2,3,4,5)
You have used follower.followers.add(*user). Hence, user must be an iterable to be unpacked and passed as a list or arguments. But user is a single User object.
You should just use follower.followers.add(user) in this case.
I am trying to update a user "karma points" whenever a user posts something. For this, i first created a new model called Myuser that allows for points property:
class Myuser(models.Model):
user=models.OneToOneField(User, on_delete=models.CASCADE)
points=models.IntegerField(default=1)
And then in my view.py post_new() function, I tried to update the score:
u=User.objects.get(username=request.user.username)
u.myuser.points=u.myuser.points+5
u.save()
but then i notice that rather than update the points field, it just saves a new instance with the same user id but updated score. I thought .save() is supposed to update exisiting copy.
This is what i did for object initiation
u=User.objects.get(username=request.user.username)
Myuser.objects.create(user_id=u.id, points=1)
Edit: I think the problem might be model initiation. When I initiate an instance and check
u=User.objects.get(username='barkthinks') #a registered username
Myuser.objects.create(user_id=u.id, points=10)
<Myuser: Myuser object (6052d3844fbcaa988e993c30)>
When I do:
Myuser.objects.all()
I will get this result
QuerySet [<Myuser: Myuser object (None)>
when I do .save(), sometimes I keep bumping into this error:
TypeError: Field 'id' expected a number but got ObjectId('6052d1054fbcaa988e993c2b').
Get the Unique Myuser instance and update the model instead
u=User.objects.get(username=request.user.username)
myuser = Myuser.objects.get(user=u)
myuser.points += 5
myuser.save()
to update any instance of a model,
variable = Models.objects.filter(conditions).update(attribute_to_update = update_value)
get the instance of the model using filter and condition, then use the .update to update values
models.py :
class Myuser(models.Model):
user=models.OneToOneField(User, on_delete=models.CASCADE)
points=models.IntegerField(default=1)
views.py :
u=User.objects.get(username='barkthinks')
new_user_instance = Myuser.objects.create(user = u , points=10)
And then in the view.py post_new() function,
my_user = MyUser.objects.get(user__id = request.user.id)
temp = my_user.points
updated_instance = Myuser.objects.get(User__id = request.user.id).update(points = temp + 10)
try at first check if there is Myuser instance if not create new one, but if there is Myuser class instance for that user, then update that instance by doing this code.
u=User.objects.get(username='barkthinks')
try:
myuser_instance = Myuser.objects.get(user=u)
myuser_instance.points += 5
myuser_instance.save()
except ObjectDoesNotExist:
Myuser.objects.create(user=u, points=10)
Can anyone explain why this is iterable:
User.objects.all()
this is valid and gives me a value (The current user's alias. session is storing the user id):
User.objects.get(id = request.session['currentuser']).alias)
But this is giving me the error saying it is 'not iterable?':
Poke.objects.get(user = User.objects.get(id = request.session['currentuser']).alias)
(This code is supposed to get a list of Poke entries where the user column matches the current user's alias.)
Here is the Poke model. It does not use ForeignKeys, as I was having trouble setting two of them without errors.
class Poke(models.Model):
id = models.IntegerField(primary_key=True)
user = models.CharField(max_length=100)
poker = models.CharField(max_length=100)
pokes = models.IntegerField()
class Meta:
app_label = "poke_app"
Get will retrieve a single object and therefore the result will not be iterable. See documentation.
Do you see an integer value when you print(request.session['currentuser'])?
If you will see a string then you shoud give an integer value
EX: userobj = User.objects.get(id=uid)
Oh sory
User.objects.get(id = request.session['currentuser']).alias)
You open ( and closed it after ['currentuser']) but why you close ) again after .alias ?
Say that I have a table called TBL_ACCOUNT which contains all of my users, and a table called TBL_EMAIL_SUBSCRIPTION where it contains the feeds that a user is subscribed to. I'm trying to make it so that there can only be one entry of each user+feed combination, so user1 can only be subscribed to feed1 once, but user1 can be subscribed to feed1 and feed2 simultaneously.
This is what my model looks like:
class TBL_ACCOUNT(BaseModel):
USERNAME = CharField(unique=True)
PASSWORD = CharField()
EMAIL = CharField(unique=True)
class TBL_EMAIL_SUBSCRIPTION(BaseModel):
USER = ForeignKeyField(TBL_ACCOUNT)
FEED = CharField()
class Meta:
indexes = (("USER_id", "FEED", True))
I have also tried just using "USER" for the indexes, but that didn't work out as the database still received duplicates.
Please refer to the peewee docs: http://docs.peewee-orm.com/en/latest/peewee/models.html#indexes-and-constraints
In your case it should look like this:
class Meta:
indexes = (
(("USER_id", "FEED"), True),
)
Note the use of commas! They are very important, because indexes are a tuple of tuples.
What is wrong with my code?
class Group(ImageModel):
title = models.CharField(verbose_name = "Title", max_length=7)
photos = models.ManyToManyField('Photo', related_name='+',
verbose_name=_('Photo'),
null=True, blank=True)
.....
pid = Photo.objects.get(image = str_path)
gid= Group.objects.get(id = self.id)
self.save_photos(gid, pid)
....
def save_photos(self, gid, pid):
group_photo = GroupPhotos(groupupload=gid.id,
photo=pid.id
)
group_photo.save()
and my GroupPhotos models is:
class GroupPhotos(models.Model):
groupupload = models.ForeignKey('Group')
photo = models.ForeignKey('Photo')
class Meta:
db_table = u'group_photos'
when i want to save it from admin panel i am getting value error sth like this:
Cannot assign "38": "GroupPhotos.groupupload" must be a "Group" instance.
with group_photo = GroupPhotos(groupupload=gid, photo=pid) defination it is working but there is no any changes in GroupPhotos table(group_photos). printing this print pid.id,' >>> ',gid.id i am getting true relation...
UPDATE:
I have been working since morning, but no progress... i have also tried this but nothing changed:
pid = Photo.objects.get(image = str_path)
ger = Group.objects.get(id = self.id)
ger.title = self.title
ger.save()
ger.photos.add(pid)
The error is here:
group_photo = GroupPhotos(groupupload=gid.id, photo=pid.id)
The arguments to groupupload and photo should be instances of Group and Photo respectively. Try the following:
group_photo = GroupPhotos(groupupload=gid, photo=pid)
In other words, when creating an object you need to pass arguments of the expected type and not an integer (which may be the primary key key of the desired object but it also might not, which is why you need to pass an object of the correct type).
i have solved my problem with adding through option to my manytomanyfield:
photos = models.ManyToManyField('Photo', related_name='+',
verbose_name=_('Photo'),
null=True, blank=True, through=GroupPhotos)
some info about ManyToManyField.through here:
Django will automatically generate a table to manage many-to-many
relationships. However, if you want to manually specify the
intermediary table, you can use the through option to specify the
Django model that represents the intermediate table that you want to
use.
The most common use for this option is when you want to associate extra data with a many-to-many relationship.