[Django]-How to insert data to django database from views.py file?

49๐Ÿ‘

โœ…

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')
๐Ÿ‘คilse2005

25๐Ÿ‘

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))
๐Ÿ‘คKristof Claes

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

5๐Ÿ‘

you may try this:

def myFunction(request):
    myObj = MyObjectType()
    myObj.customParameter = parameterX
    ...
    myObj.save()
๐Ÿ‘คPeter Grundner

Leave a comment