close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to insert data to django database from views.py file in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

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

    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:

  2. insert data to django database from views.py file

    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:

Method 1

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

Method 2

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

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read