【发布时间】:2020-02-18 10:55:59
【问题描述】:
我是 Django 新手,我正在使用 this tutorial 在我的 Web 应用程序的模型中添加多图像上传字段。到目前为止,我在如何将我的 Photo Model 关联到 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)
【问题讨论】:
-
“我被卡住了”并没有解释确切的问题是什么。你看到错误了吗?是不是发生了不该发生的事情?解释您的代码当前正在做什么,也许我们可以提供帮助。
-
代码可以上传照片,但照片与我希望的酒店模型没有关联
-
如果照片上传页面是针对特定酒店的,那么如果该页面的 URL 包含酒店的 id,例如
/hotels/<id>/photos/upload这样,您将酒店的 id 传递给视图,并可以使用该 id 获取酒店(然后您应该检查酒店是否属于当前用户,以确保)。