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:
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.
Creating objectsTo create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.
fixtures . A fixture is a collection of data that Django knows how to import into a database. The most straightforward way of creating a fixture if you've already got some data is to use the manage.py dumpdata command.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With