Monday, November 4, 2013

Re:

On Sun, Nov 3, 2013 at 8:23 PM, Aamu Padi <aamupadi@gmail.com> wrote:
> How to make a model with a yes/no field, if yes that particular object
> (image) will be used as the background, and no other image will be selected.
>
> I have come with this model:
>
> class BackgroundImage(models.Model):
> user = models.ForeignKey(user)
> caption = models.CharField(max_length=200)
> image = models.ImageField(upload_to=get_upload_file_name)
> using_image = models.BooleanField()
>
> But with this I can select all of them, and not only one.
>
> Lets take an example of profile picture. A user can have many images, but he
> can only select one as a profile picture. So, that if he selects one, the
> other will be un-select itself.
> Hope everybody understood what I mean. Please ask me if didn't understood.
> Also please correct me if my model is not correct. Thank you!
>

User can have many images, but only one profile image:

class User:
profile_image = ForeignKey('BackgroundImage', blank=True, null=True)
# other fields

class BackgroundImage:
owner = ForeignKey('User')
# other fields

# get a profile pic
image_url = user.profile_pic and user.profile_pic.image.url or ''

# set a new profile pic
image = BackgroundImage(....)
user.profile_pic = image
user.save()

User can have many images, but only one profile image, without
modifying user model

class User:
# other fields

class BackgroundImage:
owner = ForeignKey('User')
# other fields

class UserBackgroundImage:
user = OneToOneField('User')
profile_picture = ForeignKey('BackgroundImage')

# get a profile pic
image_url = user.userbackgroundimage and
user.backgroundimage.profile_picture.image.url or ''

# set a new profile pic
image = BackgroundImage(....)
user_image, created =
UserBackgroundImage.objects.get_or_create(user=user,
defaults={'profile_picture': image})
if not created:
user_image.profile_picture = image
user_image.save()

Cheers

Tom

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2Bng1g2OtAtsTb43V-JFbetP5WVtvUO_8PWUzjAFPs%3DCQ%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment