위코드 첫번째 장고 프로젝트!
My very first Django project is to create a basic poll application.
Had a tons of problem setting up on Mac OS with M1 chip.... Not too easy to deal with the latest product for me yet .. :-(
This application will consist of two parts:
I first checked if django is installed and also the version of the django by running the following command in a shell prompt
python -m django --version
If django is not installed properly, you will get an error telling "No module named django".
I first got this error. But thanks to Stackoverflow, I could fix the error.... 스택오버플로우 짱!
From the command line, we run the following command after moving into a directory where we'd like to store our code with cd
:
$ cd haileypark/
$ django-admin startproject project1
This created a project1
directory in my current directory, which is haileypark
.
*You’ll need to avoid naming projects after built-in Python or Django components. In particular, this means you should avoid using names like django (which will conflict with Django itself) or test (which conflicts with a built-in Python package).
*Where should this code live?
If your background is in plain old PHP (with no use of modern frameworks), you’re probably used to putting code under the Web server’s document root (in a place such as /var/www). With Django, you don’t do that. It’s not a good idea to put any of this Python code within your Web server’s document root, because it risks the possibility that people may be able to view your code over the Web. That’s not good for security.
Put your code in some directory outside of the document root, such as /home/mycode.
Let's see what I created in detail:
project1/
manage.py
project1/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
The outer project1/
root directory is a container for my project.
manage.py
: A command-line utility that lets you interact with this Django project in various ways.
The inner project1/
directory is the actual Python package for your project. Its name is the Python package name you'll need to use to import anything inside it (e.g. project1.urls
).
project1/__init__.py
: An empty file that tells Python that this directory should be considered a Python package.
project1/settings.py
: Settings/configuration for this Django project.
project1/urls.py
: The URL declarations for this Django project; a "table of contents" of your Django-powered site.
project1/asgi.py
: An entry-point for ASGI-compatible web servers to serve your project.
project1/wsgi.py
: An entry-point for WSGI-compatiable web server to serve your project.
Let's run the following commands after changing into the outer project1
directory.
$ python manage.py runserver
You’ll see the following output on the command line:
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
November 10, 2021 - 06:13:25
Django version 3.2.9, using settings 'project1.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
*Ignore the warning about unapplied database migrations for now; we’ll deal with the database shortly.
I’ve started the Django development server, a lightweight Web server written purely in Python. We’ve included this with Django so you can develop things rapidly, without having to deal with configuring a production server – such as Apache – until you’re ready for production.
Now’s a good time to note: don’t use this server in anything resembling a production environment. It’s intended only for use while developing. (We’re in the business of making Web frameworks, not Web servers.)
Now that the server’s running, visit http://127.0.0.1:8000/ with your Web browser. You’ll see a “Congratulations!” page as below.
Changing the port
By default, the runserver command starts the development server on the internal IP at port 8000.
If you want to change the server’s port, pass it as a command-line argument. For instance, this command starts the server on port 8080:
$ python manage.py runserver 8080
If you want to change the server’s IP, pass it along with the port. For example, to listen on all available public IPs (which is useful if you are running Vagrant or want to show off your work on other computers on the network), use:
$ python manage.py runserver 0:8000
0 is a shortcut for 0.0.0.0.
Automatic reloading of runserver
The development server automatically reloads Python code for each request as needed. You don’t need to restart the server for code changes to take effect. However, some actions like adding files don’t trigger a restart, so you’ll have to restart the server in these cases.
Now that your environment – a “project” – is set up, you’re set to start doing work.
Each application you write in Django consists of a Python package that follows a certain convention. Django comes with a utility that automatically generates the basic directory structure of an app, so you can focus on writing code rather than creating directories.
Projects vs. apps
An app is a Web application that does something – e.g., a Weblog system, a database of public records or a small poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.
Your apps can live anywhere on your Python path. In this tutorial, we’ll create our poll app in the same directory as your manage.py file so that it can be imported as its own top-level module, rather than a submodule of project1.
To create your app, make sure you’re in the same directory as manage.py and type this command:
$ python manage.py startapp polls
That’ll create a directory polls, which is laid out like this:
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
This directory structure will house the poll application.
Let’s write the first view. Open the file polls/views.py and put the following Python code in it:
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
This is the simplest view possible in Django. To call the view, we need to map it to a URL - and for this we need a URLconf
.
To create a URLconf
in the polls directory, create a file called urls.py
. Your app directory should now look like:
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
urls.py
views.py
In the polls/urls.py
file include the following code:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
The next step is to point the root URLconf
at the polls.urls
module. In project1/urls.py
, add an import for django.urls.include
and insert an include()
in the urlpatterns list, so you have:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
The include()
function allows referencing other URLconfs
. Whenever Django encounters include()
, it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.
The idea behind include()
is to make it easy to plug-and-play URLs. Since polls are in their own URLconf (polls/urls.py)
, they can be placed under “/polls/”, or under “/fun_polls/”, or under “/content/polls/”, or any other path root, and the app will still work.
When to use include()
You should always use include()
when you include other URL patterns. admin.site.urls
is the only exception to this.
You have now wired an index view into the URLconf
. Verify it’s working with the following command:
$ python manage.py runserver
Go to http://localhost:8000/polls/ in your browser, and you should see the text “Hello, world. You’re at the polls index.”, which you defined in the index view.
Page not found?
If you get an error page here, check that you’re going to http://localhost:8000/polls/ and not http://localhost:8000/.
The path()
function is passed four arguments, two required: route and view, and two optional: kwargs, and name. At this point, it’s worth reviewing what these arguments are for.
route is a string that contains a URL pattern. When processing a request, Django starts at the first pattern in urlpatterns and makes its way down the list, comparing the requested URL against each pattern until it finds one that matches.
Patterns don’t search GET and POST parameters, or the domain name. For example, in a request to https://www.example.com/myapp/, the URLconf will look for myapp/. In a request to https://www.example.com/myapp/?page=3, the URLconf will also look for myapp/.
When Django finds a matching pattern, it calls the specified view function with an HttpRequest object as the first argument and any “captured” values from the route as keyword arguments. We’ll give an example of this in a bit.
Arbitrary keyword arguments can be passed in a dictionary to the target view. We aren’t going to use this feature of Django in the tutorial.
Naming your URL lets you refer to it unambiguously from elsewhere in Django, especially from within templates. This powerful feature allows you to make global changes to the URL patterns of your project while only touching a single file.
When you’re comfortable with the basic request and response flow, read part 2 of this tutorial to start working with the database.