Skip to content

Commit

Permalink
add the remening files
Browse files Browse the repository at this point in the history
  • Loading branch information
abubakerKhaled committed Oct 30, 2024
1 parent fa6eb31 commit 83d443e
Show file tree
Hide file tree
Showing 41 changed files with 1,904 additions and 0 deletions.
Empty file added README.md
Empty file.
Binary file added bfg.jar
Binary file not shown.
22 changes: 22 additions & 0 deletions 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', 'scribly.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()
93 changes: 93 additions & 0 deletions postgresql_setup_in_django.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# Practical Steps to Set Up PostgreSQL in a Django Project

## Step 1: Install psycopg2

Install `psycopg2`, the PostgreSQL adapter for Python, by running the following command in your terminal:

```bash
pip install psycopg2
```

You can also use `psycopg2-binary` for a precompiled version:

```bash
pip install psycopg2-binary
```

## Step 2: Create a New Database

1. Log into PostgreSQL as a superuser:

```bash
psql -U postgres
```

2. Create a new database (replace `my_database` with your desired database name):

```sql
CREATE DATABASE my_database;
```

3. Exit the PostgreSQL prompt:

```sql
\q
```

## Step 3: Create a New Role

1. Log back into PostgreSQL:

```bash
psql -U postgres
```

2. Create a new role (replace `my_user` and `my_password` with your desired username and password):

```sql
CREATE ROLE my_user WITH LOGIN PASSWORD 'my_password';
```

3. Grant the new role privileges to create databases and connect to the existing database:

```sql
ALTER ROLE my_user CREATEDB;
GRANT CONNECT ON DATABASE my_database TO my_user;
```

4. Exit the PostgreSQL prompt:

```sql
\q
```

## Step 4: Connect the Role to the Database in Django

1. Open your Django project and locate the `settings.py` file.

2. Update the `DATABASES` setting to include your new database and role:

```python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'my_database', # Your new database name
'USER': 'my_user', # Your new role name
'PASSWORD': 'my_password', # Your new role password
'HOST': 'localhost', # Or your database host
'PORT': '5432', # Default PostgreSQL port
}
}
```

## Step 5: Apply Migrations

Run the following command to apply migrations and set up the database schema:

```bash
python manage.py migrate
```

## Conclusion

You have successfully set up PostgreSQL in your Django project, created a new database, created a new role, and connected that role to the database. If you encounter any issues, check the console output for error messages and ensure that your PostgreSQL service is running.
Empty file added posts/__init__.py
Empty file.
21 changes: 21 additions & 0 deletions posts/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from django.contrib import admin
from .models import Post, Comment


@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'slug', 'author', 'publish', 'status']
list_filter = ['status', 'created', 'publish', 'author']
search_fields = ['title', 'body']
prepopulated_fields = {'slug': ('title', )}
raw_id_fields = ['author']
date_hierarchy = 'publish'
ordering = ['status', 'publish']
show_facets = admin.ShowFacets.ALWAYS


@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ['name', 'email', 'post', 'created', 'active']
list_filter = ['active', 'created', 'updated']
search_fields = ['name', 'email', 'body']
6 changes: 6 additions & 0 deletions posts/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class PostsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'posts'
17 changes: 17 additions & 0 deletions posts/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from django import forms
from .models import Comment

class EmailPostForm(forms.Form):
name = forms.CharField(max_length=25)
email = forms.EmailField()
to = forms.EmailField()
comments = forms.CharField(
required=False,
widget=forms.Textarea
)


class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['name', 'email', 'body']
37 changes: 37 additions & 0 deletions posts/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Generated by Django 5.1.2 on 2024-10-24 19:18

import django.db.models.deletion
import django.utils.timezone
import uuid
from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
('users', '0001_initial'),
]

operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=250)),
('slug', models.SlugField(max_length=250, unique=True)),
('body', models.TextField()),
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('publish', models.DateTimeField(default=django.utils.timezone.now)),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('status', models.CharField(choices=[('DF', 'Draft'), ('PB', 'Published')], default='DF', max_length=2)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='blog_posts', to='users.author')),
],
options={
'ordering': ['-publish'],
'indexes': [models.Index(fields=['-publish'], name='posts_post_publish_27e544_idx')],
},
),
]
18 changes: 18 additions & 0 deletions posts/migrations/0002_alter_post_slug.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 5.1.2 on 2024-10-24 19:47

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('posts', '0001_initial'),
]

operations = [
migrations.AlterField(
model_name='post',
name='slug',
field=models.SlugField(max_length=250, unique=True, unique_for_date='publish'),
),
]
31 changes: 31 additions & 0 deletions posts/migrations/0003_comment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Generated by Django 5.1.2 on 2024-10-26 11:06

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


class Migration(migrations.Migration):

dependencies = [
('posts', '0002_alter_post_slug'),
]

operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=80)),
('email', models.EmailField(max_length=254)),
('body', models.TextField()),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('active', models.BooleanField(default=True)),
('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='posts.post')),
],
options={
'ordering': ['created'],
'indexes': [models.Index(fields=['created'], name='posts_comme_created_aa6d8f_idx')],
},
),
]
20 changes: 20 additions & 0 deletions posts/migrations/0004_post_tags.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Generated by Django 5.1.2 on 2024-10-28 20:59

import taggit.managers
from django.db import migrations


class Migration(migrations.Migration):

dependencies = [
('posts', '0003_comment'),
('taggit', '0006_rename_taggeditem_content_type_object_id_taggit_tagg_content_8fc721_idx'),
]

operations = [
migrations.AddField(
model_name='post',
name='tags',
field=taggit.managers.TaggableManager(help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags'),
),
]
Empty file added posts/migrations/__init__.py
Empty file.
75 changes: 75 additions & 0 deletions posts/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
from django.db import models
from django.urls import reverse
from django.utils import timezone
from users.models import Author
from taggit.managers import TaggableManager
import uuid


class PublishedManager(models.Manager):
def get_queryset(self):
queryset = super().get_queryset()
queryset = queryset.filter(status=Post.Status.PUBLISHED)
return queryset


class Post(models.Model):
class Status(models.TextChoices):
DRAFT = 'DF', 'Draft'
PUBLISHED = 'PB', 'Published'
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique=True, unique_for_date='publish')
author = models.ForeignKey(
Author,
on_delete=models.CASCADE,
related_name='blog_posts',
)
body = models.TextField()
uuid = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(
max_length=2,
choices=Status,
default=Status.DRAFT
)
tags = TaggableManager()

objects = models.Manager() # the default manager.
published = PublishedManager() # our custom manager.

class Meta:
ordering = ['-publish']
indexes = [
models.Index(fields=['-publish'])
]

def __str__(self) -> str:
return self.title[:50] + ("..." if len(self.title) > 50 else "")

def get_absolute_url(self):
return reverse("posts:post_detail", args=[self.uuid])


class Comment(models.Model):
post = models.ForeignKey(
Post,
on_delete=models.CASCADE,
related_name='comments'
)
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)

class Meta:
ordering = ['created']
indexes = [
models.Index(fields=['created']),
]

def __str__(self):
return f'Comment by {self.name} on {self.post}'
18 changes: 18 additions & 0 deletions posts/templates/posts/post/comment.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{% extends 'base.html' %}


{% block title %}
Add a comment
{% endblock title %}



{% block content %}
{% if comment %}
<h2>Your comment has been added.</h2>
<p><a href="{{ post.get_absolute_url }}">Back to the post</a></p>
{% else %}
{% include "posts/post/includes/comment_form.html" %}
{% endif %}
{% endblock content %}

Loading

0 comments on commit 83d443e

Please sign in to comment.