Я новичок в Django и использую этот учебник , чтобы добавить поле загрузки нескольких изображений в модель в моем веб-приложении. Пока я застрял (я не могу связать загруженные фотографии с моделью отеля. Фотографии загружаются, но не связаны с моделью отеля) о том, как связать мою фотомодель с отелями. Модель в HotelCreateView. Мой вопрос заключается в том, как мне связать это несколько изображений, поданных с моей моделью отеля, чтобы при создании отеля загруженные изображения были связаны с созданным отелем. Любезно помочь.
Большое спасибо
Модель отеля
class Hotels(models.Model):
"""Stores all the information about the hotel and also used to query hotels"""
name = models.CharField(max_length=255) #The name of the hotel
address = models.CharField(max_length=255)
city = models.CharField(max_length=255)
country = models.CharField(max_length=255)
mobile_number = models.CharField(max_length=12)
created_at = models.DateTimeField(default=timezone.now)
last_modified = models.DateTimeField(auto_now=True)
description = models.TextField()
slug = models.SlugField(unique=True)
property_photo = models.ImageField(default='default.jpg', upload_to='hotel_photos')
star_rating = models.PositiveIntegerField()
contact_person = models.ForeignKey(UserProfile, on_delete=models.SET_NULL, null=True, blank=True,) #Owner of the hotel or person who created the hotel
class Meta:
unique_together = ('name', 'slug')
verbose_name_plural = 'Hotels'
Фотомодель
class Photo(models.Model):
title = models.CharField(max_length=255, blank=True)
file = models.ImageField(upload_to='hotel_photos')
hotel = models.ForeignKey(Hotels,on_delete=models.SET_NULL, null=True, blank=True,)
class Meta:
verbose_name_plural = 'Photos'
def __str__(self):
"""Prints the name of the Photo"""
return f'{self.hotel} photos'
Forms.py
class PhotoForm(forms.ModelForm):
class Meta:
model = Photo
fields = ('hotel','file', )
Views.py
class PhotoUploadView(LoginRequiredMixin,View):
def get(self, request):
photos_list = Photo.objects.all()
return render(self.request, 'hotels/uploads.html', {'photos': photos_list})
def post(self, request):
form = PhotoForm(self.request.POST, self.request.FILES, self.request.user)
if form.is_valid():
photo = form.save(commit=False)
photo.hotel = self.request.hotel.contact_person
photo.save()
data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url}
else:
data = {'is_valid': False}
return JsonResponse(data)