如何在Django中为我的产品模型上传多张图片?

时间:2018-10-23 09:15:47

标签: django python-3.x django-models django-views

我要上传该产品的多个图像,该怎么办? Django版本为2.1,以及如何存储多个文件。 使用python3

我的模特

class Product(models.Model):
owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
name = models.CharField(max_length=33, blank=True)
description = models.TextField()
postdate = models.DateTimeField(auto_now_add=True, blank=False)
duration = models.IntegerField(null=True, blank=True)
image = models.FileField(upload_to=product_directory_path, blank=False, default='default.jpg')

我的观点

def addProduct(request):
if request.method == 'GET':
    if request.user.is_authenticated:
        return render(request, 'postAd.html')

if request.method == 'POST' and request.FILES.get('image'):
    if request.user.is_authenticated:
        user = User.objects.get(id=request.user.id)
        owner = UserProfile.objects.get(email=user.email)
        image = request.FILES.get('image')
        name = request.POST['name']
        description = request.POST['desc']
        pr = Product(owner=owner, name=name, image=image, description=description, category=category, price=price, ptype=ptype)
        pr.save()
        return HttpResponseRedirect(reverse('ors:dashboard')) 

2 个答案:

答案 0 :(得分:1)

你可以在模型中试试这个:

class Product(models.Model):
  owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
  name = models.CharField(max_length=33, blank=True)
  description = models.TextField()
  postdate = models.DateTimeField(auto_now_add=True, blank=False)
  duration = models.IntegerField(null=True, blank=True)
  image = models.FileField(upload_to='/image/, blank=False, 
  default='default.jpg')

class ImageProduct(models.Model):
  Product=models.ForeignKey(Product,on_delete=models.CASCADE)
  image=models.imageField(upload_to='/image/')

参考: https://medium.com/ibisdev/upload-multiple-images-to-a-model-with-django-fd00d8551a1c

答案 1 :(得分:0)

  

forms.py

from django import forms

class UploadFileForm(forms.Form):
    file_1 = forms.FileField()
    file_2 = forms.FileField()
    ....
    ....
    file_n = forms.FileField()
  

在您的html文件中添加以下代码,以便从forms.py获取文件属性。

 {{ form.file1 }} #for 1st file 
 {{ form.file2 }} #for 2nd file
  

在views.py和以下代码中添加以下代码   无需在GET方法(请求)中检查用户身份验证。

def addProduct(request):
    if request.method == 'GET':
        return render(request, 'postAd.html')

    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            file = request.FILES['file1']
            file1 = request.FILES['file2']

            #convert byte code to string 
            file_str = file.read().decode("utf-8")
            file_str1 = file1.read().decode("utf-8")
        return render(request, "postAd.html")

您可以浏览该项目,以获取有关上传多个文件的更多详细信息。click here