Django: ManyToMany association not working - django

models.py
class Gallery(models.Model):
name = models.CharField(max_length=100)
class Image(models.Model):
in_gallery = models.ManyToManyField(Gallery, blank=True)
title = models.CharField(max_length=100)
class ImageInGallery (models.Model):
image = models.ForeignKey(Image, blank=True, null=True, on_delete=models.DO_NOTHING)
gallery = models.ForeignKey(Gallery, blank=True, null=True, on_delete=models.DO_NOTHING)
Click to view the screenshot of my admin page of adding a Gallery
Click to view the screenshot of my admin page of adding an Image
Have a look at the screen shot....
(ignore the fields that I didn't show in models.py code for simplicity) See the difference I have in admin page of adding a Gallery and Image..... I cannot add image to Gallery
How to fix this?

what's the purpose of ImageInGallery ?
You have to use through argument.
Since you define ManyToManyField in Image you already have a bilateral relation.
If you want all galleries related to an image1 instance of Image you can do a :
image1.galleries.all()
If you want images related to gallery1 instance of Gallery, you can do :
galleries.image_set.all()
In documentation, your Gallery is 'Publication' and Image is 'Article'.

Related

Why my model field is getting prepopulated in admin?

I have created a model as below.
class UserPost(models.Model):
author = models.ForeignKey(User, related_name='userpost', null=True, on_delete=models.CASCADE)
post_date = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=150, blank=False)
post_body = models.TextField(blank=True, null=True, default='text')
image = models.ImageField(upload_to='post_pics', blank=True)
likes = models.ManyToManyField(User, blank=True, related_name='post_likes')
I am not populating likes field anywhere, my admin screenshot is below.Why my likes field is getting populated with all the users created?
admin screenshot
admin.py
from django.contrib import admin
from feed.models import UserPost
# Register your models here.
admin.site.register(UserPost)
Edit 1:
Adding a screenshot for Rishabh's answer.
trying to add user from left as suggested by him
You are using ManyToManyField of Django which will show you all records of User table left side and you can add them by double clicking on them or by clicking '+' sign, so your likes field is not prepopulated at all it is just showing User table data.

Django, select image from previous uploaded images

I have a Post model which has a ImageField.
class Post(models.Model):
headline = models.CharField(max_length=255)
lead = models.TextField(blank=True, null=True)
body = models.TextField(blank=True, null=True)
image = models.ImageField(upload_to="posts", blank=True, null=True, max_length=255)
In my ModelForm, the file input for the image works perfectly, but I was wondering how to let the user choose between uploading a new image, or selecting one from all the images that have been previously uploaded to the site.
Any pointers?
In order to do that define another model Image and then create a foreign key from Post to Image. When creating a new post, you can either select an existing image or upload a new one and then select it.

Add multiple objects of same model at the same time in the django admin

I have a model to upload pictures:
class Snap(models.Model):
image = models.ImageField(upload_to=get_upload_file_name)
caption = models.CharField(max_length=150, blank=True, null=True)
pubdate = models.DateTimeField(default=timezone.now)
In the admin it contains all the Snap's field (i.e. one field to upload an image ,its caption and the pubdate) which is as expected. How do I add multiple record of Snap's in one go. I hope I was clear, if not please ask. Your help and guidance will be very much appreciated. Thank you.
admin.py:
class SnapAdmin(admin.ModelAdmin):
class Meta:
model = Snap
admin.site.register(Snap, SnapAdmin)

Creating list of photos in Django

On the webpage I am currently working on I have to display profiles of different persons. Each person has a profile image that is displayed on the right side. Furthermore, I have the content saved as markdown on the server.
Now I want to add the possibility to add an optional list of images that are displayed under the text and shows something about the person. My model for the person looks like that:
class stipendiat(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
content = models.TextField()
year = models.IntegerField(blank=False, null=False)
form = models.IntegerField(blank=False, null=False)
image = models.ImageField(upload_to='stipendiaten/', blank=True, null=True, default='default.jpg')
gallery = # This is the question
def __unicode__(self):
return self.first_name + " " + self.last_name
Because I want to save some data about the image the model should look like that:
class Image(models.Model):
caption = models.CharField(max_length=512)
year = models.IntegerField()
image = models.ImageField(upload_to=upload_path_handler, blank=False, null=False)
For convenience it should be possible to add an image while editing the form for the person. To be precise, I want to add a person and fill in the necessary information (first_name, last_name, content etc.). At the end should be a list of connected images and a button to add an image rapidly.
Is it necessary to use an external app or is there an elegant solution with relation fields?
Maybe you should use a different model for the gallery images and a foreign key field to link the two models together
class Image(models.Model):
#...
stipendiat = models.ForeignKey(Reporter)
Now you can retrieve the Gallery Images for a stipendiat with id 1 like this
Image.objects.filter(stipentiat__pk=1)

Django - how to make ImageField/FileField optional?

class Product(models.Model):
...
image = models.ImageField(upload_to=generate_filename, blank=True)
When I use ImageField(blank=True) and do not select image into admin form, an exception occurs.
In django code you can see this:
class FieldFile(File):
....
def _require_file(self):
if not self:
raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
def _get_file(self):
self._require_file()
...
Django trac has ticket #13327 about this problem, but seems it can't be fixed soon. How to make these field optional?
blank=True should work. If this attribute, which is False by default, is set to True then it will allow entry of an empty value.
I have the following class in my article app:
class Photo(models.Model):
imagename = models.TextField()
articleimage = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True)
I make use of the above class in another class by using the ManyToManyField relationship:
class Article(models.Model):
pub_date = models.DateTimeField(default=timezone.now)
slug = models.SlugField(max_length=130)
title = models.TextField()
photo = models.ManyToManyField(
Photo, related_name='photos', blank=True)
author = models.ForeignKey(User)
body = models.TextField()
categories = models.ManyToManyField(
Category, related_name='articles', null=True)
I want to make images in my articles optional, so blank=True in
photo = models.ManyToManyField(Photo, related_name='photos', blank=True)
is necessary. This allows me to create an article without any images if I want to.
Are you using class Product in any relationship? If so, make sure to set blank=True in the relationship you are using.
Set null=True (see documentation)
class Product(models.Model):
...
image = models.ImageField(upload_to=generate_filename, blank=True, null=True)
If 'optional' means that you want to be able to disregard the image field altogether. Then blank=True, so do the trick. However, if you are still getting the same error, then this means that you are using it's url either in the template somewhere or you are trying to open the path of the image in models.py or views.py ( may be to resize the image or some other backend preprocessing).
That is why it is always suggested to use try - catch block while handling files.