简体   繁体   English

Django 如何将图像上传到表单

[英]Django How to Upload an Image to Form

This is my code associated with the form:这是我与表单关联的代码:

# models

class Date(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    place = models.ForeignKey('Place', on_delete=models.CASCADE, null=True)
    title = models.CharField(max_length=64, null=True)


class Photo(models.Model):
    date = models.ForeignKey('Date', on_delete=models.CASCADE)
    image = models.ImageField(verbose_name='Photos', upload_to='media/date/photos/')

# form

class DateForm(forms.ModelForm):
    image = forms.ImageField()
    class Meta:
        model = Date
        exclude = ('user',)

# view

class CreateDateView(LoginRequiredMixin, CreateView):
    template_name = 'app/date/form.html'
    form_class = DateForm

    def form_valid(self, form):
        form.instance.user = self.request.user
        form.save() # by the way why do I save this form? Is it okay to save it in form_valid method?
        photos = self.request.FILES.getlist('image')
        for photo in photos:
            Photo.objects.create(image=photo)
        return super().form_valid(form)

The issue is how to save Photo objects if it requires a Date model id.问题是如果需要Date模型 ID,如何保存 Photo 对象。 It raises NOT NULL constraint failed: app_photo.date_id As I understand I have to write something like:它引发了NOT NULL 约束失败:app_photo.date_id据我了解,我必须编写如下内容:

Photo.objects.create(date=date_from_the_form, image=photo)

But how to get the pk from the Date model?但是如何从 Date 模型中获取 pk 呢? Hope you understand my problem, if any questions don't hesitate to write down below in comments section.希望您理解我的问题,如果有任何问题,请随时在评论部分写下。 Thanks in advance!提前致谢!

Error错误

You need to create the date object first.您需要先创建日期对象。 Also, is each date going to be unique?另外,每个日期都是独一无二的吗? If so, you need to change your model Meta declarations to include unique_together .如果是这样,您需要更改模型元声明以包含unique_together

You also need to avoid the for loop when creating each object.创建每个对象时,您还需要避免 for 循环。 It's very expensive because it's going to make a round trip to the database for each save() called.它非常昂贵,因为每次调用 save() 都会往返于数据库。 That's what bulk_create is for, which limits your database touches to one command to make many objects.这就是bulk_create的用途,它将您的数据库接触限制为一个命令来创建多个对象。

Here's pseudocode to get you going:这是让你开始的伪代码:

if len(photos) > 0:  # don't create a date if there aren't photos
  date = Date() # add your arguments

  filtered = Date.objects.filter(date=date)

  date = date.create() if not filtered.exists() else date = filtered[0]  # but this is potentially dangerous if you risk duplicate dates. Only use this if you know it's the correct date
  photos = [Photo(date=date,image=p) for p in photos]
  Photo.objects.bulk_create(photos)

Good luck!祝你好运!

You need save the photo object:您需要保存照片对象:

def form_valid(self, form):
    form.instance.user = self.request.user
    form.save() # by the way why do I save this form? Is it okay to save it in form_valid method?
    photos = self.request.FILES.getlist('image')
    for photo in photos:
        temp = Photo.objects.create(image=photo)
        temp.save()
    return super().form_valid(form)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM