This content originally appeared on DEV Community and was authored by Bee
on day four of django learning i created a simple project following these steps
Pre-requisites
- Python installed
- Basic command-line knowledge install django on your terminal run
pip install django
1.
Start a Django Project
In your terminal:
django-admin startproject myproject
cd myproject
python manage.py startapp restaurant
python manage.py startapp shop
myproject is the project name
shop and restaurant are the names of the site i wanted to create
Now, my structure looks like this :
open shop and it will display this
-
admin.py
: Configuration for the Django admin interface. -
apps.py
: Configuration for the app itself. -
models.py
: Contains the database models for the app. -
tests.py
: Contains tests for the app. -
views.py
: Contains the request/response logic for the app. -
migrations/
: Contains database migrations for the app
2.
Register the App
Open myproject/settings.py
, find INSTALLED_APPS
, and add ' shop'and 'restaurant'
:
INSTALLED_APPS = [
...
'shop',
'restaurant',
]
this is how it looks!
3.
Create a shop Model
we shall start with shop model
In shop/models.py
:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
def __str__(self):
return self.title
Then run:
python manage.py makemigrations
python manage.py migrate
4.
Register Model in Admin
In shop/admin.py
:
from django.contrib import admin
from .models import Post
admin.site.register(Post)
here is how it looks
Create a superuser:
python manage.py createsuperuser
Run the server:
python manage.py runserver
Go to http://127.0.0.1:8000/admin/
and add a few blog posts!
5. Show Posts in the Browser
In shop/views.py
:
from django.shortcuts import render
from .models import Post
def home(request):
posts = Post.objects.all()
return render(request, 'shop/home.html', {'posts': posts})
Create a file: shop/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='blog-home'),
]
Link it in your main myproject/urls.py
:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('shop/', include('shop.urls')),
]
6.
Create a Template
Create folders:
shop/templates/shop/home.html
Then add:
<!DOCTYPE html>
<html>
<head>
<title>My shop</title>
</head>
<body>
<h1>shop Posts</h1>
{% for post in posts %}
<h2>{{ post.title }}</h2>
<p>{{ post.goods }}</p>
<hr>
{% endfor %}
</body>
</html>
Done!
Now visit:
http://127.0.0.1:8000/shop/
And boom — your shop model will appear!
This content originally appeared on DEV Community and was authored by Bee