Python 如何从views.py文件向django数据库插入数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35602049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:40:04  来源:igfitidea点击:

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

pythondjangodjango-modelsdjango-viewspymysql

提问by niloofar

How can I insert data to my django database from a function in the views,py file? Is python manage.py shellthe only way to insert?

如何从 views,py 文件中的函数向我的 django 数据库插入数据?是python manage.py shell唯一的插入方式吗?

For more explanations I'm using:

有关我正在使用的更多解释:

  • python 3.4
  • django 1.8.2
  • PyMySQL
  • 蟒蛇 3.4
  • Django 1.8.2
  • pymysql

For example:

例如:

models.py:

模型.py:

from django.db import models

class Publisher(models.Model):
    name = models.CharField(max_length=30)
    city = models.CharField(max_length=60)

views.py:

视图.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

网址.py

from niloofar.views import send

url(r'^index/', send),

从 niloofar.views 导入发送

url(r'^index/', 发送),

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 shellthen:

让我注意到,即使我跑了python manage.py shell

from books.models import Publisher

p = Publisher(name='Apress', city='Berkeley')

p.save()

从 book.models 导入 Publisher

p = Publisher(name='Apress', city='Berkeley')

p.save()

nothing will be inserted to django database.

不会向 Django 数据库插入任何内容。

采纳答案by ilse2005

Your question is very unclear. You should probably go through the django-tutorial.

你的问题很不清楚。您可能应该阅读django-tutorial

But sure you can insert data into the db from views. Assume you have a model called Foo:

但是确保您可以从视图中将数据插入到数据库中。假设您有一个名为 的模型Foo

models.py

模型.py

class Foo(models.Model):
    name = models.CharField(max_length=100)

view.py

查看.py

from .models import Foo

def some_name(request):
    foo_instance = Foo.objects.create(name='test')
    return render(request, 'some_name.html.html')

回答by Kristof Claes

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

回答by Peter Grundner

you may try this:

你可以试试这个:

def myFunction(request):
    myObj = MyObjectType()
    myObj.customParameter = parameterX
    ...
    myObj.save()

回答by Tanishq Vyas

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.

一个简单的方法是使用 create 函数。通过提及字段名称及其值。以下图示代码可帮助您将数据从 views.py 插入数据库并将数据库内容显示到 html 页面中。

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

models.py 看起来像这样

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

所以 views.py 看起来像

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

下面应该是home.html文件,显示所有输入的数据

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