How to insert data to django database from views.py file?

niloofar picture niloofar · Feb 24, 2016 · Viewed 94.4k times · Source

How can I insert data to my django database from a function in the views,py file? Is python manage.py shell the only way to insert?

For more explanations I'm using:

  • python 3.4
  • django 1.8.2
  • PyMySQL

For example:

models.py:

from django.db import models

class Publisher(models.Model):
    name = models.CharField(max_length=30)
    city = models.CharField(max_length=60)

views.py:

from django.http import HttpResponse
import pymysql
from books.models import Publisher

def send(request):
    p = Publisher(name='Apress', city='Berkeley')
    p.save()

urls.py

from niloofar.views import send

url(r'^index/', send),

I want when the page index is loaded, the send function works and insert data to database.

It does not work. It does not give any error and also nothing happened when i refreshed the index page, nothing was sent to database. I think there is mistake in syntax, in the way i'm trying to insert data.

Let me notice that even when I run python manage.py shell then:

from books.models import Publisher

p = Publisher(name='Apress', city='Berkeley')

p.save()

nothing will be inserted to django database.

Answer

ilse2005 picture ilse2005 · Feb 24, 2016

Your question is very unclear. You should probably go through the django-tutorial.

But sure you can insert data into the db from views. Assume you have a model called Foo:

models.py

class Foo(models.Model):
    name = models.CharField(max_length=100)

view.py

from .models import Foo

def some_name(request):
    foo_instance = Foo.objects.create(name='test')
    return render(request, 'some_name.html.html')