32

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.

Community
  • 1
  • 1
niloofar
  • 2,244
  • 5
  • 23
  • 44
  • 1
    Of course the shell isn't the only way to write to the db, what would be the point of that? In any case, the tutorial shows you exactly how to do this; please go through it fully. – Daniel Roseman Feb 24 '16 at 12:26
  • 1
    Welcome to stackoverflow, 'http://stackoverflow.com/questions/35472057/django-user-input-steps-needed/35472962#35472962' Get started with django tutorial first. – Kamlesh Feb 24 '16 at 12:31
  • It's not enough to just write "it does not work". What's happening exactly? How does it differ from your expectations? Do you get any error messages? What do they say? From your code example it looks like you forgot to name your view (there should be a name before the parenthesis in the line `def (request):`) – Ludwik Trammer Feb 24 '16 at 13:14

4 Answers4

48

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')
Jamie Bull
  • 12,889
  • 15
  • 77
  • 116
ilse2005
  • 11,189
  • 5
  • 51
  • 75
  • With `publisher_instance = Publisher.object.create(name='test')` It show this error `type object 'Publisher' has no attribute 'object'`. – niloofar Feb 24 '16 at 13:10
  • Sorry, there was a typo. It should be `Publisher.objects.create(name='test')` (objects not object). I edited my answer – ilse2005 Feb 24 '16 at 13:23
  • I tried `def send(request):` `publisher_instance = Publisher.objects.create(name='tux')` `return HttpResponse("done")` and the "done" word printed in the page but nothing was sent to db – niloofar Feb 24 '16 at 13:28
  • Well I don't know how but it worked after rebooting system, thanks. – niloofar Feb 24 '16 at 14:52
  • @niloofar, if the answer helped you, please accept it. Thanks! – ilse2005 Feb 25 '16 at 12:28
24

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))
Community
  • 1
  • 1
Kristof Claes
  • 10,797
  • 3
  • 30
  • 42
11

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])

Tanishq Vyas
  • 1,422
  • 1
  • 12
  • 25
5

you may try this:

def myFunction(request):
    myObj = MyObjectType()
    myObj.customParameter = parameterX
    ...
    myObj.save()
Peter Grundner
  • 319
  • 2
  • 8