Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django 如何将图像字段设置为可选?_Django_Django Templates - Fatal编程技术网

Django 如何将图像字段设置为可选?

Django 如何将图像字段设置为可选?,django,django-templates,Django,Django Templates,如何将图像字段设置为可选?我正在尝试将图像字段设置为可选(无或选定)。在提交表单时,图像字段没有抛出“多值错误”。我想将此图像字段设置为“无”。 models.py class Profile(models.Model): first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null

如何将图像字段设置为可选?我正在尝试将图像字段设置为可选(无或选定)。在提交表单时,图像字段没有抛出“多值错误”。我想将此图像字段设置为“无”。 models.py

class Profile(models.Model):
    first_name = models.CharField(max_length=255, blank=True, null=True)
    last_name = models.CharField(max_length=255, blank=True, null=True)
    image = models.ImageField(upload_to='images', blank=True, null=True)
forms.py


    class Meta:
        model = Profile
        fields = '__all__'
views.py

def profile(request):
    if request.method == 'POST':
       form = ProfileForm(request.POST)
       if form.is_valid:
          first_name = request.POST.get('first_name')
          last_name = request.POST.get('last_name')
          image = request.FILES['images']
          file_storage = FileSystemStorage()
          obj = Profile(first_name=first_name, last_name=last_name, image=file_storage.save(image.name, image))
          return render(request, 'index.html',{})
       return render(request, 'index.html',{})
    return render(request, 'index.html',{})
index.html

<form action="#" method="post" enctype="multipart/form-data">
      {% csrf_token %}
      <input type="text" name="first_name" class="form-control form-control" id="fname">
      <input type="text" name="last_name" class="form-control form-control" id="lname">
      <input type="file" name="images" class="form-control" id="image">
      <button type="submit" class="btn btn-primary mt-5 mb-5">Save</button>
</form>

{%csrf_令牌%}
拯救

使用与其他字段相同的方法:

image = request.FILES.get('images')
如果请求中不存在image,则这将使image=None。然后:

image_saved = None
if image is not None:
  image_saved = FileSystemStorage().save(image.name, image)
obj = Profile(first_name=first_name, last_name=last_name, image=image_saved)