0

I have started coding in Python using Django and MySql recently.So, I am facing issue in simple inserting data(JSON format) in a table in MySql database.I have tried few things which I am mentioning below.But it did not work.And I am using the following - Python, Django Framework, MySql Database, mysqlclient connector, Rest API Framework, Postman. Please help me out with suggestions.

from django.shortcuts import render, redirect
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import fetchdata
from .serializers import fetchdataSerializers
from rest_framework import status,response
from rest_framework import viewsets
from django.http import HttpResponse

@api_view(['GET','POST'])

def index(request):

 if request.method=='POST':

    try:
        _json = request.json
        _name = _json['name']
        _email = _json['email']
        _password = _json['pwd']
        sql = "INSERT INTO tbl_user(user_name,user_email,user_password) 
        VALUES(%s,%s,%s)"
        data = (_name, _email, _password,)
        conn = mysql.connect()
        cursor = conn.cursor()
        cursor.execute(sql, data)
        conn.commit()
        resp = jsonify('User added successfully!')
        serializer=fetchdataSerializers(data=request.data)

         if serializer.is_valid():

          serializer.save()

  return resp
  return Response(serializer.data,status=status.HTTP_201_CREATED)
  return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
4
  • You are doing stuff that Django already does for you. Please read about Django's ORM: docs.djangoproject.com/en/2.2/topics/db/models and follow some Django tutorials to get more grip of the framework. Commented Jun 19, 2019 at 13:12
  • Thanks a lot for the support...I have checked the documentation link provided by you...but I am confused about few things...first is where will I write this part of the code ......."" >>> p = Person(name="Fred Flintstone", shirt_size="L") >>> p.save() >>> p.shirt_size 'L' >>> p.get_shirt_size_display() 'Large '""..................as I am using VS ...so I wrote it in terminal...but it's not working...AND second thing is...Isn't it possible to post data from POSTMAN?@Juho Rutila Commented Jun 20, 2019 at 5:22
  • Are you using the django shell? python manage.py shell Commented Jun 20, 2019 at 10:30
  • No, I am using "python manage.py runserver"......but i have also checked using "python manage.py shell".....then too it is giving error...the error is...."" In [1]: p = importdata(first_name = "jj") --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-1-98b08ca14697> in <module> ----> 1 p = importdata(first_name = "jj") NameError: name 'importdata' is not defined ""...... @Juho Rutila Commented Jun 20, 2019 at 13:09

1 Answer 1

1

You can add a fixtures folder in your app and place the Json file in it. The Json file might be something like this category.json

[
    {
      "model": "category",
      "pk": 1,
      "fields": {
        "name": "person",
        "created_at": "2019-05-06T09:27:51.386383",
        "updated_at": "2019-05-06T09:27:51.386383"
      }
    },

  ]

Run python manage.py loadata category.json. Depending on how you plan to implement this, you can run this command after your migration. Check the Doc to understand more

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot for replying...I have tried this, but an error is coming. The error says...."" in Deserializer raise DeserializationError() from exc... django.core.serializers.base.DeserializationError: Problem installing fixture 'C:\Users\Rounak-\Python_Projects\blog_p_root\importdata\fixtures\importdata.json': "".......Can you suggest anything please?? @Anthony Ugwu
I think it has to do with the fixture you created, make sure there are no discrepancies between your fixture and the database schema
I created a folder in my app called " fixtures "...The app name is "importdata"...inside the fixtures folder I created a json file named "importdata.json"...Now this file contains ...""" [{ "model": "importdata", "pk": 1, "fields": { "first_name": "jj", "email": "jj", }}, {same as previous array}}] """"...and in my model.py the class name is "" importdata"...and in the database the table migrated has the name..."" importdata_importdata"""...So, this is the details...can you please help me out by pointing out my mistake...????? @Antony Ugwu

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.