Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Django Shell

Your next step is to put data in your database. For this, you’re going to use the Django shell to put one project in your database. Head over to your terminal and start the Django shell by typing the following:

$ python manage.py shell

This opens up a terminal, but it has the Django settings already imported, so it allows you to work directly from the root folder of a Django project.

00:00 Next, we want to put some data into our database. For this, we’re going to use the Django shell. There’s some different ways of doing that, but I want to show you this very handy tool. We’re going to get started and put one Project into our database.

00:15 For this, I head over to my terminal, in here. I’m going to start the Django shell by typing python manage.pyas so often—and then shell. This opens up a terminal.

00:30 However, it has the Django settings already imported, so it allows you to work directly from the root folder of a Django project. So, if you want to do something within Django or with the database, then start your shell like this. Now, what I want to do is I want to create a Project object and put this one into the database. For this, I’m going to use Django’s ORM. So, here is our cheatsheet.

00:57 That’s what a Project instance is going to look like. It’s going to have a title, description, technology, and image—an image path.

01:05 We put the images already in here. So, let’s go ahead and just create one. What we need to be able to use, then, is we have to import this Project model.

01:16 We can find this inside of—let me close this for a moment—projects/ and then models.py. Okay, so this is where it sits. I’m going to say from projects.models import Project, and now I can create a Project.

01:37 So, my first project is going to be a Project instance that has a title.

01:45 It’s going to be "test project".

01:50 It’s going to have a description

02:03 Yada, yada, I’m just going to fill this out. Make sure that you put in the right data types. Like, it’s clear that we’re going to use text for a CharField (character field), TextField, and you can’t go over the max_length or it’s going to complain, et cetera.

02:28 And for image, I’m just going to put in

02:32 the name of the image file as the rest of the path—you remember Django knows about static/ folders in all apps, and we told it about projects/ and img/, so we directed it from here to img/.

02:45 All I need to put in here is, really, the name of the image file. So, I’m going to say "testproject.png". Okay. This is my first Project instance. Let’s create it.

03:02 Cool. So, all done? Not quite. What we need to do first—similar to the migrations—there’s always a step in between before you actually commit something to the database. So what I need to do to put it into the database is I have to say p1.save().

03:22 And now, I have this one instance as a row sitting inside of my database. We can inspect this with this visual tool that I showed you before, go ahead and do that. I’m going to show you a different way of doing it, which is I can query here. So, I can say results = Project.objects.all().

03:43 With this, I’m retrieving all the Project objects from the database, and now I can look at this. It’s telling us it’s a QuerySet instance, as a result, and it contains one Project object.

03:58 Awesome! I can say, “Give me that first one.” I can say results[0] is going to be my p1let’s call it different, just to—p, for this one.

04:13 I can say p.title, for example, and this is 'test project'. It’s what I just put in there—so, what I did. And that’s where we can see the power of using an object-relational mapper. Using Python, I created an object, then I simply said .save() to put it into my relational database, and here I’m—again—using the ORM to query the database, get some results back, and then you can see, I can access them again very similar—or, in the same way that I would access a Python object.

04:47 So that’s the ORM at work, and yeah, we put a Project inside of our database. So, let’s make sure to set up the rest that we need. We still need routes, we need views, and we need templates. Let’s make sure to set those up so that we can actually see this Project, also on the front end.

Pygator on Oct. 13, 2019

But how would you practically populate your data base if you had 1000s or millions of sample rows?

Martin Breuss RP Team on Oct. 16, 2019

Good question! As a beginner project, this assumes that you’re building a small example project and that you’ll fill up your DB as you build out your portfolio.

However, Django does have capabilities to integrate with an existing database, and since it’s all Python code, you could also write a custom script that fetches the data from your source and funnels it into your project’s DB.

reblark on Oct. 24, 2019

Wait. You copied image files from your own server, which, of course, I can’t do. How can I get copies of those? It is really important to me that I can replicate what your are demonstrating.

Martin Breuss RP Team on Oct. 24, 2019

@reblark: I took some screenshots right on my computer and moved those files into the Django folder structure that you see above. The path that you see points to the relative path in the Django project. This could be any image file that you have locally, you just need to make the names match.

reblark on Nov. 4, 2019

OK. I don’t see the screenshots or the structure and I apologize for not being able to keep my comments in synch but it is difficult only being able to communicate through a specific session. It’s 11/4 at 11:00 AM PST, and I just wanted you to know that I worked through the PyCharm database problem. On the one hand, it is very frustrating. On the other hand, figuring things out is very rewarding. It’s all effing crazy.

Gaurav yadav on Dec. 7, 2019

Are there any ways by which we can enter data through frontend interface?

Martin Breuss RP Team on Dec. 7, 2019

Yes, you can use the Admin Interface that comes provided with a Django app.

Otherwise, you’ll have to built your own Django Forms to collect user input.

Siggi Berg on Dec. 29, 2019

The database doesn’t work in my project. This is how the Django shell looks:

from projects.models import Project p1 = Project(title=”test project”,description = “This is a test, 1234”,technologi=”Django”, image=”F-01.jpg”) p1.save <bound method Model.save of <Project: Project object (None)>>

Her somtething seems to have gone wrong. Anyway I continued. But nothing seems to have been inserted into the database: *>>> results = Project.objects.all()

results <QuerySet []>

*

Siggi Berg on Dec. 29, 2019

I’m sorry! I found that I had spaces in the “project.models” command. Also I forgot the () after the p1.save. Now everything is working fine.

koutsellisthemistoklis on March 1, 2020

1) When you write p1 = Projects(title=’test project’, ....)

where is the model.Models argument of Projects class?

Also, another question.

2) In Projects class declaration, variables: title, escription, technology, image shouldn’t be self.title, self.escription, self.technology, self.image instead?

Martin Breuss RP Team on March 1, 2020

Hi @koutsellisthemistoklis!

1) Inheritance

What you are doing with the below code:

from django.db import models

class Project(models.Model):
    # your code

is that you are inheriting properties from Django’s Model class to the new model you are creating. Therefore, models.Model is not an argument that you would need to pass when creating an instance of a class. Classes work differently in this than functions do. Check out our article on Inheritance and Composition: A Python OOP Guide and the section in our associated course.

2) Missing self in Django Models

The very stripped-down and somewhat unusual way of defining a class in a Django model is due to the fact that Django has metaclasses that actually take on the work of creating your class.

This allows the class definition to be so clean and easy. Note that you also don’t have to write an explicit __init__() method for a model class.

All this is thanks to metaclasses and Django’s gargantuous workload behind the scenes that aims to make webdev easier for you :)

okorobright13 on April 12, 2020

(InteractiveConsole)

from projects.models import project Traceback (most recent call last): File “<console>”, line 1, in <module> ImportError: cannot import name ‘project’ from ‘projects.models’ (C:\Users\Dell\PycharmProjects\django-portfol io\projects\models.py)

please how can i resovle this thanks to progress

Martin Breuss RP Team on April 13, 2020

Hi @okorobright13! Looks like this might be a typo. Your Project model should be capitalized instead of in lowercase.

You want to import the Project class that you defined in projects/models.py, therefore your import statement needs to make sure it can actually find it. Computers are very literal with spelling and capitalization, so it’ll only find it if it matches exactly :) Hope that fixes it!

okorobright13 on April 13, 2020

Martin Breuss,thanks alot you are right is working now and i’m in progress for now,hahahahaha message error is our friend!!!!!1

jacob6 on April 20, 2020

>>> p1 = Project(title="test project", description="this is a test 1234!", technology="Django", image="avatar.jpg"
... p1.save()
  File "<console>", line 2
    p1.save()
     ^
SyntaxError: invalid syntax

What is going on there? I’ve been staring at it for a long time, and I can’t find the error.

jacob6 on April 20, 2020

Nevermind. I found the error. It turns out you have to be very precise with parenthesis and notation! =oP

Martin Breuss RP Team on April 20, 2020

It’s a tricky one, because the arrow doesn’t point in the right place here.

Check the end of the line above where the ^ is pointing to, there’s a little thing missing…

You can notice that there’s something wrong by how the prompt starts the line where you’re writing p1.save(), it should start with a >>>, but insteads starts with a .... The thee dots mean that it’s continuing the line above.

Hope that helps you find it! :)

c4inmypants on July 27, 2020

Hey! So I have a weird question. So in the part after p1.save() I did results = project.objects.all and when I did >>>results I got this : <bound method BaseManager.all of <django.db.models.manager.Manager object at 0x03B899D0>>

I realise my mistake was not adding the () at the end and everything was fine. So my question is what does the () tell python to do? I tried googling what the shell spit out the time I did the command without () but I couldn’t find anything too helpful. Could someone explain to me I am just very curious.

Martin Breuss RP Team on July 27, 2020

Hi @c4inmypants and nice job figuring it out and staying curious :)

The short answer to your question is that in Python, the () execute a function or a method.

Functions And Methods

Functions and methods have some, well, functionality encoded in them that can be accessed by calling them. That’s why using the () at the end of their name is called a Function Call. In your case, to be all the way precise, you’d have to talk about a “method” instead of “function” because the code that does the work is dependent on a specific object. 🙄 Don’t worry about that too much, however, for this situation, that’s mostly terminology. But if you want, you can read more about Difference Between a Method And a Function.

Your Example

So when you read that the () execute the method, it might make you think that there needs to be something to execute. That is the object that you are referring to and that contains the code logic. Let’s look at your example, stripped away from the variable assignment:

project.objects.all

Here you are referencing the all method on your projects.objects object, but you are not calling it. For all that Python knows, you want to access the method, and not to execute it. So it does your bidding and tells you what you got:

<bound method BaseManager.all of <django.db.models.manager.Manager object at 0x03B899D0>>

You can dive deeper into this output and learn a fair bit from it, but the main take-aways for this example are:

  1. Reference, not execution: When leaving out the brackets, Python gives you access to the bound method BaseManager.all of some object that lives in your computer’s memory
  2. Execution: If you want to make the method do its job, you need to call it, which you do by adding the () at the end, e.g.:
projects.objects.all()

redxking on Sept. 1, 2020

The instructor set the query to p1 so after running: p1 = Project(title="test project", description="this is a test 1234!", technology="Django", image="testproject.png")

Run: p1.save()

Then: p1

Become a Member to join the conversation.