[英]Django How to Upload an Image to 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)
問題是如果需要Date模型 ID,如何保存 Photo 對象。 它引發了NOT NULL 約束失敗:app_photo.date_id據我了解,我必須編寫如下內容:
Photo.objects.create(date=date_from_the_form, image=photo)
但是如何從 Date 模型中獲取 pk 呢? 希望您理解我的問題,如果有任何問題,請隨時在評論部分寫下。 提前致謝!
您需要先創建日期對象。 另外,每個日期都是獨一無二的嗎? 如果是這樣,您需要更改模型元聲明以包含unique_together
。
創建每個對象時,您還需要避免 for 循環。 它非常昂貴,因為每次調用 save() 都會往返於數據庫。 這就是bulk_create
的用途,它將您的數據庫接觸限制為一個命令來創建多個對象。
這是讓你開始的偽代碼:
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)
祝你好運!
您需要保存照片對象:
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.