0

As my image option is optional , I want to save it even if the file is not uploaded as it is optional, but it is giving me error as it is not able to receive the image. How can I save it in the database even if that field is empty? and even in case if we have multiple optional values how to receive and save those null type entries in data base?

#Model
    class Recommendations(models.Model):
        Name = models.CharField(max_length=100)
        Company = models.CharField(max_length=100, null=True)
        Designation = models.CharField(max_length=100, default='Null')
        Message = models.TextField(null=False)
        image = models.ImageField(upload_to='Recommender', default='default.png', blank=True)
        check = models.BooleanField(default=False)


    # Views Code to receive the data through a form

    def recommend(request):
        if request.method == 'POST':
            try:
                name = request.POST['name']
                company = request.POST['company']
                designation = request.POST['designation']
                message = request.POST['message']
                image = request.FILES['photo']
                recom = Recommendations(Name=name,Company=company,Designation=designation, Message=message, image=image)
                recom.save()
                messages.success(request,'Recommendation Recieved')
                return redirect('/')
            except Exception as problem:
                print(problem)
                messages.error(request, problem)
                return redirect('/')

1 Answers1

0

Instead of accessing data by request.POST['field'] (or request.FILE['name']), you should get the data by using the dictionary's get() method. This way, you can define values (None by default) to assign to your variables if you receive empty fields, thus preventing KeyError.

I would implement something like this:

def recommend(request):
        if request.method == 'POST':
            try:
                data = {
                    'name': request.POST.get('name'),
                    'company': request.POST.get('company'),
                    'designation': request.POST.get('designation'),
                    'message': request.POST.get('message'),
                    'image' = request.FILES.get('photo')
                }
                data = {k: v for k, v in data.items() if v}
                recom = Recommendations(**data)
                recom.save()
                messages.success(request,'Recommendation Recieved')
                return redirect('/')
            except Exception as problem:
                print(problem)
                messages.error(request, problem)
                return redirect('/')
revliscano
  • 2,227
  • 2
  • 12
  • 21