Django JSON not being saved in sqlite database

Hello everyone

I am trying to save JSON data to sqlite database on Django

I have these small code chunks here which are giving me some problems.

Here is a chunk of my models.py file

class Recipes(models.Model):
    name = models.CharField(max_length=120, default='')
    pub_date = models.DateTimeField('date published')
    style = models.CharField(max_length=200, default='')
    brewer = models.CharField(max_length=100, default='')
    type = models.CharField(max_length=20, default='All Grain')
    version = models.CharField(max_length=20, default='1')
    batch_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0)
    boil_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0)
    boil_time = models.DecimalField(decimal_places=1, max_digits=4, default=0.0)
    efficiency = models.DecimalField(decimal_places=1, max_digits=4, default=75.0)
    ibu = models.DecimalField(decimal_places=1, max_digits=4, default=0.0)
    abv = models.DecimalField(decimal_places=2, max_digits=4, default=0.0)
    notes = models.TextField(default='')
    carbonation = models.DecimalField(decimal_places=2, max_digits=4, default=0.0)
    primary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0)
    secondary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0)
    age = models.DecimalField(decimal_places=1, max_digits=4, default = 0)
    __fermentables = []
  
    @classmethod
    def create(cls,attr):
        recipe = cls()
        # do something with the book
        for k in Recipes._meta.fields:
            if  k.name in attr:
                setattr(recipe,k.name,attr[k.name])
        return recipe

Here is the part of views.py which is giving me trouble

def saveRecipe(request):
        try:
            data=json.loads(request.read())
            print("printing values")
            print(data["name"])  #prints here works
            recipe = Recipes.create(attr=data)
            recipe.name = data["name"]
            recipe.save()
            recipe.addYeast(items=data["yeast"])
            recipe.addFermentables(items=data["fermentables"])
            recipe.addHops(items=data["hops"])
            recipe.addMashStep(items=data["mash"])
            return  HttpResponse(serialize('json', [recipe]),  content_type='application/json')
        except:
           
            return HttpResponse("error")

Basically I have a button which parses JSON from filled forms and when I print name print(data["name"]) it seems to be parsed correctly.

Now for testing purposes I put recipe.save() in the part of the views file where you can see and I think that it is technically supposed to save the parsed information into the database but when I check the database there is nothing there.

I tried doing this without the try/except block, however then I get this error:

Internal Server Error: /save-recipe
Traceback (most recent call last):
  File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Admin\Desktop\praktika\brew\brewery\views.py", line 106, in saveRecipe
    recipe = Recipes.create(attr=data)
  File "C:\Users\Admin\Desktop\praktika\brew\brewery\models.py", line 73, in create
    print(name, style)
NameError: name 'name' is not defined
[26/Mar/2022 19:30:21] "POST /save-recipe HTTP/1.1" 500 67750

So basically my question is why is the recipe.save() not doing what it’s supposed to and what is missing in order to save the data correctly?

Thank you in advance!

You’ve trimmed something from your code that you posted.

Notice that the actual error is in models.py line 73

I see no line that looks like that in your code.

Here is more of my models.py file:

class Recipes(models.Model):
    name = models.CharField(max_length=120, default='')
    pub_date = models.DateTimeField('date published')
    style = models.CharField(max_length=200, default='')
    brewer = models.CharField(max_length=100, default='')
    type = models.CharField(max_length=20, default='All Grain')
    version = models.CharField(max_length=20, default='1')
    batch_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0)
    boil_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0)
    boil_time = models.DecimalField(decimal_places=1, max_digits=4, default=0.0)
    efficiency = models.DecimalField(decimal_places=1, max_digits=4, default=75.0)
    ibu = models.DecimalField(decimal_places=1, max_digits=4, default=0.0)
    abv = models.DecimalField(decimal_places=2, max_digits=4, default=0.0)
    notes = models.TextField(default='')
    carbonation = models.DecimalField(decimal_places=2, max_digits=4, default=0.0)
    primary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0)
    secondary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0)
    age = models.DecimalField(decimal_places=1, max_digits=4, default = 0)
    __fermentables = []
  
    @classmethod
    def create(cls,attr):
        recipe = cls()
        # do something with the book
        for k in Recipes._meta.fields:
            if  k.name in attr:
                setattr(recipe,k.name,attr[k.name])
        return recipe
    @classmethod
    def addFermentables(self,items):

       for itm in items:
           
           self.__fermentables.append(itm)
         
           return self.__fermentables

    @classmethod
    def addHops(self,items):
       for i in items:
           return i

    @classmethod
    def addYeast(self,items):
       for i in items:
           return i

    @classmethod
    def addMashStep(self,items):
       for i in items:
           return i

The line 73 is actually return recipe in the create method of Recipes

There are more classes in the models.py file. However, they aren’t related to this so I left them out.

But that’s not the line shown in the traceback.

You’re not running the code you think you’re running…

Extremely weird…

You mean that it shows the line as print(name, style) ?

There is no such line in my models.py file and I don’t have any other models.py files on my entire computer…

And also the location of the file is correct. That is exactly where my models.py file is.

Is there something else that could cause this?

Did you ever have that line in your file, and did you stop / restart your server after taking it out? How are you running the server?

I didn’t have that line…

I am running the server with the command prompt by using python manage.py runserver

I just tested this again without the try block and now I am not getting any errors just this:

[26/Mar/2022 20:57:33] "GET /recipes HTTP/1.1" 200 59557
[26/Mar/2022 20:57:33] "GET /static/assets/bootstrap/js/i18n/defaults-lt_LT HTTP/1.1" 404 1876
printing values
Tauras
[26/Mar/2022 20:57:40] "POST /save-recipe HTTP/1.1" 200 346

However, the data is still not in the database when I open in it with sqlite viewer

There’s probably some issue associated with your classmethods interfering with the normal metaclass functioning of your model. (Just a guess)

(Also, your add... methods aren’t really class methods.)

That’s really not how you want to do that. You want to create your create method (and probably by a different name) in a custom manager - not within the model class itself.

Methods on your model are intended to be written for existing instances of that model. Methods on your manager are intended for either building the instances or for working on multiple instances.

You probably want to rework that model.

Django Model classes are heavily metaclass driven. There are many ways in which they don’t work like typical Python classes. You’re best off not trying to treat them as such.

Thank you for the advice.

However, the issue is that those add methods are not part of what I am trying to save to the database so they shouldn’t be the ones causing this problem.

I am just trying to save the base Recipe at the moment. So this still keeps me wondering how I should go about fixing this issue …

Fix your model.

You are likely interfering (somehow) with the normal mode of operation of Model instance creation.