Skip to content

Commit

Permalink
Add code steps for Dwitter series (realpython#236)
Browse files Browse the repository at this point in the history
* Add code steps for part 2

* Add code for part 1

* Add code for part 3

* Add code steps for part 4

* Language edit

* Language edit

* Language edit and clarification

* Language edit and clarification

* Language edit and clarification

* Language edit and clarification

Co-authored-by: Sadie Parker <[email protected]>
  • Loading branch information
martin-martin and spacerest authored Dec 15, 2021
1 parent c17c4a4 commit be9455e
Show file tree
Hide file tree
Showing 359 changed files with 8,523 additions and 0 deletions.
57 changes: 57 additions & 0 deletions dwitter-part-1/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Dwitter - Your tiny social network built with Django

This web app models the basic functionality of Twitter.

You can:

- **Post** short text-based messages
- **View** all users on the platform
- **Follow** and unfollow other users
- **Inspect** a feed of messages from users that you follow

Follow the [step-by-step instructions](https://realpython.com/django-social-network-1/) on _Real Python_ to build your own version of Dwitter.

## Setup

You can run the provided example project on your local machine by following the steps outlined below.

Create a new virtual environment:

```bash
python3 -m venv venv
```

Activate the virtual environment:

```bash
source ./venv/bin/activate
```

Navigate to the folder for the step you're currently on.

Install the dependencies for this project if you haven't installed them yet:

```bash
(venv) $ python -m pip install -r requirements.txt
```

Make and apply the migrations for the project to build your local database:

```bash
(venv) $ python manage.py makemigrations
(venv) $ python manage.py migrate
```

Create a superuser that allows you to log in to your Django admin portal:

```bash
(venv) $ python manage.py createsuperuser
```

Run the Django development server:

```bash
(venv) $ python manage.py runserver
```

Navigate to `http://localhost:8000/admin` and log in with your superuser credentials. You can create users through the Django admin and explore your social media platform with multiple users.
Empty file.
18 changes: 18 additions & 0 deletions dwitter-part-1/source_code_final/dwitter/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from django.contrib import admin
from django.contrib.auth.models import User, Group
from .models import Profile


class ProfileInline(admin.StackedInline):
model = Profile


class UserAdmin(admin.ModelAdmin):
model = User
fields = ["username"]
inlines = [ProfileInline]


admin.site.unregister(User)
admin.site.register(User, UserAdmin)
admin.site.unregister(Group)
6 changes: 6 additions & 0 deletions dwitter-part-1/source_code_final/dwitter/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class DwitterConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "dwitter"
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Generated by Django 3.2.8 on 2021-10-08 09:55

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

initial = True

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.CreateModel(
name='Profile',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('follows', models.ManyToManyField(blank=True, related_name='followed_by', to='dwitter.Profile')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
Empty file.
23 changes: 23 additions & 0 deletions dwitter-part-1/source_code_final/dwitter/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User


class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
follows = models.ManyToManyField(
"self", related_name="followed_by", symmetrical=False, blank=True
)

def __str__(self):
return self.user.username


@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
user_profile = Profile(user=instance)
user_profile.save()
user_profile.follows.add(instance.profile)
user_profile.save()
3 changes: 3 additions & 0 deletions dwitter-part-1/source_code_final/dwitter/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# from django.test import TestCase

# Create your tests here.
3 changes: 3 additions & 0 deletions dwitter-part-1/source_code_final/dwitter/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# from django.shortcuts import render

# Create your views here.
22 changes: 22 additions & 0 deletions dwitter-part-1/source_code_final/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "social.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)


if __name__ == "__main__":
main()
4 changes: 4 additions & 0 deletions dwitter-part-1/source_code_final/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
asgiref==3.4.1
Django==3.2.5
pytz==2021.3
sqlparse==0.4.2
Empty file.
16 changes: 16 additions & 0 deletions dwitter-part-1/source_code_final/social/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for social project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "social.settings")

application = get_asgi_application()
128 changes: 128 additions & 0 deletions dwitter-part-1/source_code_final/social/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
"""
Django settings for social project.
Generated by 'django-admin startproject' using Django 3.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = (
"django-insecure-+kqax213*#kt^9jxpmb&+h0pheb-r!o-@+8evi7((j03&dmiqk"
)

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"dwitter",
]

MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "social.urls"

TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]

WSGI_APPLICATION = "social.wsgi.application"


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = "/static/"

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
21 changes: 21 additions & 0 deletions dwitter-part-1/source_code_final/social/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""social URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path

urlpatterns = [
path("admin/", admin.site.urls),
]
16 changes: 16 additions & 0 deletions dwitter-part-1/source_code_final/social/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for social project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "social.settings")

application = get_wsgi_application()
Empty file.
13 changes: 13 additions & 0 deletions dwitter-part-1/source_code_step_01/dwitter/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from django.contrib import admin
from django.contrib.auth.models import User, Group


class UserAdmin(admin.ModelAdmin):
model = User
# Only display the "username" field
fields = ["username"]


admin.site.unregister(User)
admin.site.register(User, UserAdmin)
admin.site.unregister(Group)
6 changes: 6 additions & 0 deletions dwitter-part-1/source_code_step_01/dwitter/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class DwitterConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "dwitter"
3 changes: 3 additions & 0 deletions dwitter-part-1/source_code_step_01/dwitter/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# from django.db import models

# Create your models here.
3 changes: 3 additions & 0 deletions dwitter-part-1/source_code_step_01/dwitter/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# from django.test import TestCase

# Create your tests here.
3 changes: 3 additions & 0 deletions dwitter-part-1/source_code_step_01/dwitter/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# from django.shortcuts import render

# Create your views here.
Loading

0 comments on commit be9455e

Please sign in to comment.