Python Forum
Save JSON data to sqlite database on Django
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Save JSON data to sqlite database on Django
#1
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:


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!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Django: View is unable to find attributes of database model pythonpaul32 0 535 Dec-07-2023, 06:38 PM
Last Post: pythonpaul32
  Webscrape using RPi and SQlite database, always write the last value in database Armond 0 528 Jul-19-2023, 09:11 PM
Last Post: Armond
  trying to save data automatically from this page thunderspeed 1 2,026 Sep-19-2021, 04:57 AM
Last Post: ndc85430
  DJANGO Looping Through Context Variable with specific data Taz 0 1,839 Feb-18-2021, 03:52 PM
Last Post: Taz
Question wkhtmltoimage generated jpeg save to Database using mongoengine Madoo 2 3,095 Aug-18-2020, 03:42 PM
Last Post: Madoo
  How to make data coming from a database clickable giving more details newbie1 8 3,770 May-29-2020, 11:19 PM
Last Post: newbie1
  Extract json-ld schema markup data and store in MongoDB Nuwan16 0 2,474 Apr-05-2020, 04:06 PM
Last Post: Nuwan16
  Send email to gmail after user fill up contact form and getting django database updat Man_from_India 0 2,121 Jan-22-2020, 03:59 PM
Last Post: Man_from_India
  how to save the data from MySQL to CSV in Flask farah97 4 2,954 Jan-03-2020, 03:02 AM
Last Post: farah97
  how retrieve database save multiple data in web Django 2.1 taomihiranga 0 2,813 Jul-30-2019, 04:58 PM
Last Post: taomihiranga

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020