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

Question:

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.

Asked By: niloofar

||

Answers:

You can just create an instance of one of your models and save it. Suppose you have an Article model:

from django.http import HttpResponse
from django.template import loader

from .models import Article


def index(request):
    article = Article()
    article.title = 'This is the title'
    article.contents = 'This is the content'
    article.save()

    template = loader.get_template('articles/index.html')
    context = {
        'new_article_id': article.pk,
    }
    return HttpResponse(template.render(context, request))
Answered By: Kristof Claes

you may try this:

def myFunction(request):
    myObj = MyObjectType()
    myObj.customParameter = parameterX
    ...
    myObj.save()
Answered By: Peter Grundner

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')
Answered By: ilse2005

An easy way to do this would be to make use of create function. By mentioning the field name and their values. The following illustrated code helps you to insert data into your database from views.py and display the contents of database into the html page.

Suppose we have a table which looks something like this

Name      Age     Marks
Bunny      4       10
Tanishq    12      12

The models.py looks something like this

from django.db import models

# Create your models here.
class Student(models.Model):

    student_name = models.CharField(max_length = 120)
    student_age = models.IntegerField()
    student_marks = models.IntegerField()

So the views.py would look something like

from django.shortcuts import render
from .models import Student    # Student is the model class defined in models.py

# Assuming the data to be entered is presnet in these lists
stud_name = ['Aman', 'Vijay']
stud_age = [13, 12]
stud_marks = [20, 22]

def my_view(request, *args, **kwargs):
    
    # Iterate through all the data items
    for i in range(len(stud_name)):

        # Insert in the database
        Student.objects.create(Name = stud_name[i], Age = stud_age[i], Marks = stud_marks[i])


    # Getting all the stuff from database
    query_results = Student.objects.all();

    # Creating a dictionary to pass as an argument
    context = { 'query_results' : query_results }

    # Returning the rendered html
    return render(request, "home.html", context)


The following should be the home.html file to display all entered data

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>

<body>
<h1>HOME</h1>

<table>
    <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Marks</th>
      
    </tr>
    {% for item in query_results %}
        <tr> 
            <td>{{ item.student_name }}</td>
            <td>{{ item.student_age }}</td>
            <td>{{ item.student_marks }}</td>
            
        </tr>
    {% endfor %}
</table>

</body>
</html>


Below change required for the insert, otherwise you will get type error

Student.objects.create(stud_name = stud_name[i], stud_age = stud_age[i], stud_marks = stud_marks[i])

Answered By: Tanishq Vyas