[Answer]-Django – How to access the different classes with its User?

0👍

First, watch out for User model that has changed since Django 1.5 : you can now provide a User model without linking to Django “user” class.

Then, there are 2 things you can do :

(as Peter explained)

ProfilePic.objects.filter(user=m)

When you do not want to link the pic to the user (but rather link the user to the pic)

class User (models.Model):
    pic = models.ForeignKey(Pic)

class Pic (models.Model):
    picture = models.ImageField(upload_to=get_upload_file_name)

u = User.objects.get(pk=42)
u.pic # --> gives you the one picture that a user can have

p = Pic.objects.get(pk=42)
p.user_set # --> gives you 0 to (many) users that have this pic linked to it.

if Each User can have many pictures and every pictures can have many users, what you want is “many_to_many_field”.

If you want an avatar for the user, use a picture in the “User” object.
If you want to have several pictures for the user (as in “album”) use the ForeignKey to a picture model.
If you want to have several pictures linked to several user (as in “mark as favourite”), use many to many.

Then, for copying a file to an other file, use this kind of things :

from PIL import Image
class MyImages(models.Model):
      photo_one = models.ImageField(upload_to="one/", blank=True, null=True)
      photo_two = models.ImageField(upload_to="two/", blank=True, null=True)
      def copy(self):
           self.photo_two.save(self.photo_one.name, ContentFile(file(self.photo_one.path).read()))

1👍

One simple way would be just to filter directly on your inherited models:

ProfilePic.objects.filter(user=m)

I can’t recall offhand if the related _set syntax you’re using works with inherited models in any form or not.

You also have foreign keys defined for profile_pic and background_pic on your UserProfile model – if you’re trying to access those images, they work as normal for foreign keys:

m.profile_pic

I am not sure why you have both foreign keys and a specialized subclass that does nothing.

Leave a comment