I am new to Django and I ran into a problem when I tried enable the admin to add multiple images to a user profile at once.
I created a Model Profile that allows a user to have one profile, and each profile has more than one photo.
I want to use user_id to link photos to profile and use user_id for filter. However, when I tried to upload more than one photo to a profile, it displays error “Please correct the errors below.”
The following are my models and classes I added to the admin.py
models.py
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL, null=True,
)
GENDER_CHOICES = (
('F', 'Female'),
('M', 'Male')
)
date_of_birth = models.DateField(blank=True, null=True)
gender = models.CharField(max_length=1,
default='F',
blank=False,
choices=GENDER_CHOICES
)
about_me = SizedTextField(
size_class=2,
null=True,
blank=True
)
date_created = models.DateTimeField(default=timezone.now)
class Photos(models.Model):
user = models.ForeignKey(
Profile,
to_field='user',
null=True,
blank=True,
on_delete=models.SET_NULL
)
photo = models.ImageField(
upload_to='photos/%Y/%m/%d/',
blank=True
)
admin.py
class PhotosInline(admin.TabularInline):
model = Photos
fk_name = 'user'# only one photo allowed to be uploaded when I specify this, I want more than one
@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
list_display = ['user', 'date_of_birth','gender', 'about_me']
inlines = [PhotosInline,]
Why does it only allow one photo to be uploaded? Photos Model has Many to One relationship with Profile and it must allow more than one photo to be uploaded to a profile. What must I do to solve the problem?
I just reset migration, deleted two tables in the MySQL database and did the migration again. I found out that the first time I successfully uploaded one or more photos at once to a profile, it worked as I expected. But after that it does not allow me to upload any more photo to the profile in admin “inlines” form.