Home > Enterprise >  Making a post http request of form data to a database with empty/blank fields
Making a post http request of form data to a database with empty/blank fields

Time:01-02

I have a consumer model with several fields, where I have also specified their default values; e.g.

age = models.CharField(default="no information", max_length=50)

I use the following snippet to post a new consumer to my MongoDB database:

if request.method == 'POST':
        try:
            consumer_data = JSONParser().parse(request)
            consumer_serializer = ConsumerModelSerializer(data=consumer_data)
            if consumer_serializer.is_valid():
                consumer_serializer.save()
                collection_name.insert_one(consumer_serializer.data)
                response = {
                    'message': "Successfully uploaded a consumer with id = %d" % consumer_serializer.data.get('id'),
                    'consumers': [consumer_serializer.data],
                    'error': ""
                }
                return JsonResponse(response, status=status.HTTP_201_CREATED)
            else:
                error = {
                    'message': "Can not upload successfully!",
                    'consumers': "[]",
                    'error': consumer_serializer.errors
                }
                return JsonResponse(error, status=status.HTTP_400_BAD_REQUEST)
        except:
            exceptionError = {
                'message': "Can not upload successfully!",
                'consumers': "[]",
                'error': "Having an exception!"
            }
            return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

When I fill out all the fields on my Angular form and post, everything works fine. However, when I leave a field blank, I get a bad request error message and the post does not go through.

Initially, I thought it was because I did not have default fields in my Django model, but even after I added them, I still get this.

How can I modify the code snippet to allow me to post with blank fields?

This not only saves me time in testing and filling out the form many times, but also a user of the app might actually leave some fields blank...

CodePudding user response:

Simply add blank=True and make sure there is a default parameter also:

age = models.CharField(default="no information", max_length=50, blank=True)
  • Related