无法在Django中存储多个图像

时间:2018-07-28 09:44:33

标签: python django

我正在用Django开发酒店预订网络应用程序。问题是我用外键引用完美地编写了模型。我遇到的主要问题是与此reference有关。

在我的Web应用程序中,我需要一个上传图像的进度条。为此,我已经包含了给定参考中的代码,但是问题是,当我上传图像时,图像没有被存储。

这是我的模特:

hotel_rating_choices  = (
('1','1'),
('2','2'),
('3','3'),
('4','4'),
('5','5'),
('6','6'),
('7','7'),
)

class Hotel(models.Model):

    Hotel_Name = models.CharField(max_length=50)
    location = models.CharField(max_length=20)
    no_of_rooms = models.IntegerField()
    room_price = models.IntegerField()
    rating = models.CharField(max_length=1, choices=hotel_rating_choices, default=3)
    hotel_main_img = models.FileField(upload_to='hotel_images/')
    uploaded_at = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)

    def __str__(self):
        return self.Hotel_Name

class Hotel_image(models.Model):

    hotel_img = models.ImageField(upload_to = 'hotel_images/', blank = True, null = True)
    hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, related_name="hotel_images")

这是我的表单:

class add_hotel(forms.ModelForm):

class Meta:
    model = Hotel
    fields = ('Hotel_Name', 'location', 'rating','no_of_rooms', 'room_price', 'hotel_main_img', )

    widgets = {
        'hotel_main_img' : forms.ClearableFileInput(attrs={'multiple': True})
    }

这是我的观点:

class BasicUploadView(FormView):

template_name = 'photos/basic_upload/index.html'
model = Hotel
form_class = add_hotel
success_url = reverse_lazy('home')

def get(self, request, *args, **kwargs):

    form = add_hotel
    return render(
            self.request,
            template_name = self.template_name,
            context={'form' : form}
         )

def post(self, request, *args, **kwargs):

    form = self.form_class(self.request.POST, self.request.FILES)
    if form.is_valid():

        Hotel_Name = form.cleaned_data['Hotel_Name']
        location = form.cleaned_data['location']
        no_of_rooms = form.cleaned_data['no_of_rooms']
        room_price = form.cleaned_data['room_price']
        rating = form.cleaned_data['rating']
        hotel_main_img = form.cleaned_data['hotel_main_img']
        now = datetime.datetime.now()
        uploaded_at = now.strftime("%Y-%m-%d %H:%M:%S")
        user = request.user

        hotel_object = Hotel.objects.create(Hotel_Name = Hotel_Name, location = location, no_of_rooms = no_of_rooms, room_price = room_price, rating = rating,
                                            hotel_main_img = hotel_main_img, uploaded_at = uploaded_at, user = user)

        hotel_images_list = form.files.getlist('hotel_main_img')
        for image in hotel_images_list:
            Hotel_image.objects.create(hotel_img = image, hotel = hotel_object)

        return redirect('home')

    return render(request, self.template_name, {'form': form})

images_list仅包含一幅图像,其余图像未存储。

这是我遇到问题的主要原因模板页面:

<div align="center">
<button type="button" class="btn btn-primary js-upload-photos">
  Upload photos
</button>
  <input id="fileupload" type="file" name="hotel_main_img" multiple
       style="display: none;"
       data-url="{% url 'basic_upload' %}"
       data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>
</div>

我没有上传完整的HTML页面,但是主要部分是与此有关的,而问题仅在于此,正如博客中所指定的,我已将其命名为 hotel_main_img ,但这是就我而言不起作用。

这是我的页面:

enter image description here

当我通过浏览按钮上传时,主图像正在成功上传,但是当我通过“上传照片”按钮进行上传时,图像不会被存储。我不知道图像要上传到哪里。当我通过ipdb进行调试时,在hotel_main_img中只有一个映像,其余映像都丢失了。请帮助我解决这个问题。

1 个答案:

答案 0 :(得分:0)

您的问题是,在您的Hotel模型上,您拥有hotel_main_img,它的定义是models.FileField(upload_to='hotel_images/'). So not only is it not an ImageField , it's a FileField` ...但是它不是列表的图片...这是为您的表单呈现的单个文件上传,对于自动表单处理也是如此

您将需要为相关Hotel_image对象创建一个包含内联表单的表单集。然后,您可以上传多张图片。