Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 385
niloofar Avatar asked Feb 24 '16 12:02

niloofar


People also ask

How does Django store data in database?

Creating objectsTo create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.

What is fixture in Django?

fixtures . A fixture is a collection of data that Django knows how to import into a database. The most straightforward way of creating a fixture if you've already got some data is to use the manage.py dumpdata command.


1 Answers

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') 
like image 72
ilse2005 Avatar answered Sep 28 '22 03:09

ilse2005