简体   繁体   English

Django 如何正确上传图像到表单?

[英]Django How to properly upload 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 them down below in the comments section.希望您能理解我的问题,如果有任何问题,请不要犹豫,在下面的评论部分写下来。 Thanks in advance!提前致谢!

Error错误

When you call form.save() it returns model instance so you can get instance from it like this当您调用form.save()时,它会返回模型实例,因此您可以像这样从中获取实例

def form_valid(self, form):
    form.instance.user = self.request.user
    date_instance = form.save() 
    photos = self.request.FILES.getlist('image')
    for photo in photos:
       Photo.objects.create(date=date_instance, image=photo)
    return super().form_valid(form)

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

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