[英]How can I not put data in ImageField in Django?
I am to store images in imagefield.我要将图像存储在 imagefield 中。 But I don't want to print out an error even if I don't put an image in ImageField.
但是即使我没有在 ImageField 中放置图像,我也不想打印出错误。 In other words, I want to leave ImageField null.I also tried null=True and blank=True to do this, but it didn't work properly.
换句话说,我想让 ImageField 为 null。我也尝试过 null=True 和 blank=True 来做到这一点,但它没有正常工作。 What should I do to make it possible?
我应该怎么做才能使它成为可能? Here is my code.
这是我的代码。
class post (models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=40)
text = models.TextField(max_length=300)
image1 = models.ImageField(blank=True, null=True)
image2 = models.ImageField(blank=True, null=True)
image3 = models.ImageField(blank=True, null=True)
image4 = models.ImageField(blank=True, null=True)
image5 = models.ImageField(blank=True, null=True)
To correctly use an ImageField()
you need to install Pillow with pip install Pillow
要正确使用
ImageField()
您需要使用pip install Pillow
It would be better to make an Image model and reference it with a ForeignKey from your Post model like this:最好制作一个 Image 模型并使用 Post 模型中的 ForeignKey 引用它,如下所示:
from django.db import models
class Image (models.Model):
title = models.CharField(max_length=40)
text = models.TextField(max_length=300)
image = models.ImageField(blank=True, null=True)
def __str__(self):
return self.title
class Meta:
db_table = 'image'
class Post (models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
images = models.ForeignKey(Image, on_delete=models.CASCADE, related_name='posts')
title = models.CharField(max_length=40)
text = models.TextField(max_length=300)
def __str__(self):
return self.title
class Meta:
db_table = 'post'
Django will try and upload an image to the Media root, so add the MEDIA_URL
to the bottom of your settings.py
like this: Django会尝试和上传图片到媒体的根,所以添加
MEDIA_URL
到您的底部settings.py
是这样的:
# settings.py
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Dont forget to clear your database and redo your migrations and you should be able to keep the ImageField empty if you want不要忘记清除数据库并重做迁移,如果需要,您应该能够将 ImageField 保持为空
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.