user1862399
user1862399

Reputation: 217

How to insert data to django database without forms

Hi I am trying to insert data to the database in django without forms.

This is my views.py file

def updatetrans(request):
    json_data=open('/home/ttt/Abc/a.json').read()
    data = json.loads(json_data)
    for pk, pv in data.iteritems():
    for k,v in pv.iteritems():
        try:
             print k, " =>> ", pv['transcript'][1]
        except:
            pass

This is my url.py file

url(r'^updatetrans/$', 'booki.account.views.updatetrans', name='updatetrans'),

Here is my models.py file. I have created two tables. And want to insert data in both of them separately.

class TransType(models.Model):
    name = models.TextField()
    def __unicode__(self):
        return self.name

class Trans(models.Model):
    trans = models.ForeignKey(TransType)
    script = models.CharField(max_length=200)
    def __unicode__(self):
        return self.trans

I am getting the output on console. That output I want to save to the database. Plz help.

Thank you.. I tried some other way. I am getting error as:

global name 'TransType' is not defined
Not inserted ==> e

My code:

def updatetrans(request):
    json_data=open('/home/ttt/Ali/a.json').read()
    data = json.loads(json_data)
    for pk, pv in data.iteritems():
        for k,v in pv.iteritems():
            try:
                trans_type = TransType.objects.get_or_create(name=k)
                trans = Trans()
                trans.trans_id = trans_type.id
                trans.script = pv[k][1]
                trans.save()
                print " Inserted ==>", pv[k][1]
            except Exception, e:
                print e
                print "Not inserted ==>", pv[k][1]
                pass
            return HttpResponse("Done")

Upvotes: 0

Views: 17861

Answers (4)

Muhammad Ali
Muhammad Ali

Reputation: 1

Since I have been doing the same thing..

For example:

models.py

class Dataset(models.Model):
    hash = models.CharField(max_length=32)
    category = models.CharField(max_length=10)

views.py

 if request.method == "POST":
    uploaded_file = request.FILES['document']
    fs = FileSystemStorage()
    fs.save(uploaded_file.name,uploaded_file)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    media_path = os.path.join(BASE_DIR,'dataset')
    full_path=os.path.join(media_path,uploaded_file.name)
    f = default_storage.open(full_path, 'r')
    data = f.read()
    for i in data.split("\n"):
        hash,category = i.strip("\n").split(",")
        Dataset.objects.create(hash=hash,category=category)
        print("yes")
    f.close()

Conclusion

You just specify your models and then create with what variable or column that you have.

MODELS.objects.create(column1=data1,column2=data2)

Example inside of my file

12345678,good
12345678,bad

Upvotes: 0

user1862399
user1862399

Reputation: 217

The problem is solved. The answer is as follows. To Store the records in the django database without using any input or form. To avoid duplicate entries in the database.

This is my views.py file

def updatetrans(request):
      json_data=open('/home/ttt/Ali/a.json').read()
      data = json.loads(json_data)
      for pk, pv in data.iteritems():
            for k,v in pv.iteritems():
                  try:
                        trans_type = TransType.objects.get_or_create(name=k)
                        trans = Trans()
                        trans.transtype_id = trans_type[0].id
                        if isinstance(pv[k], basestring):
                              script = pv[k]
                        else:
                              print "****** List ****"
                              script = pv[k][1]
                        trans.script = script
                        trans.save()
                        print " Inserted ==>", script
                  except Exception, e:
                        print e
                        #print "Not inserted ==>", pv[k][1]
                        pass
      return HttpResponse("Done")

This is my models.py file.

class TransType(models.Model):
      name = models.TextField()
      created = models.DateTimeField(auto_now_add = True)
      updated = models.DateTimeField(auto_now = True) 
      def __unicode__(self):
          return self.name

class Trans(models.Model):
      transtype = models.ForeignKey(TransType)
      script = models.CharField(max_length=200)
      created = models.DateTimeField(auto_now_add = True)
      updated = models.DateTimeField(auto_now = True) 
      class Meta:
            unique_together = (("transtype", "script"),)
      def __unicode__(self):
          return self.trans

Upvotes: 4

ChandyShot
ChandyShot

Reputation: 307

You can do it using Model.objects.create()

Let's say you're receiving data from post form and want to save in QuillModel, here's how to do it in python2 django

from __future__ import unicode_literals

from django.http import HttpResponse
from django.shortcuts import redirect, render

from .forms import TemplateForm

from .models import QuillModel

def app3(request):
    if request.method == "POST":
        print(request.POST)
        html_content = request.POST.get('html_content')
        input_area = request.POST.get('input_area')

        if html_content and input_area:
            obj = QuillModel.objects.create(html_content=html_content, input_area=input_area)
            obj.save()

        return redirect('/app3/app3')

    else:
        form = TemplateForm()
        return render(request, 'app3/forms/f1_post_form.html', {'form' : form})

See the if request.method == "POST": part for saving into database.

Upvotes: 1

WeizhongTu
WeizhongTu

Reputation: 6424

You just want to save data to database, so you can do it like this easily

>> cd project_directory
>> python manage.py shell
>> from xxx.models import TransType,Trans
>> tt = TransType.objects.create(name='read from file')
>> Trans.objects.create(trans=tt, script='read from file')

or write a python script to import data to database, put it in your project directory,run python manage.py shell then import yourscript

if you don't like python manage.py shell, just set DJANGO_SETTINGS_MODULE environment, then just run python yourscript in terminal. Such as

import os
os.environ["DJANGO_SETTINGS_MODULE"] =  "yoursite.settings"

# The above two lines could be written simply as:
# from project.wsgi import *

from xxx.models import import TransType,Trans
TransType.objects.create()
Trans.objects.create()

remember to replace xxx with your app name

see QuerySet API:https://docs.djangoproject.com/en/dev/ref/models/querysets/#create

Chinese people could see here (other people could just read the code): http://www.ziqiangxuetang.com/django/django-import-data.html

Upvotes: 2

Related Questions