Skip to content

Feat/announcement #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 12 additions & 26 deletions blog/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
# Generated by Django 3.0.5 on 2020-04-21 12:32
# Generated by Django 4.2.10 on 2024-03-26 02:08

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


class Migration(migrations.Migration):

initial = True

dependencies = [
Expand All @@ -15,30 +16,15 @@ class Migration(migrations.Migration):

operations = [
migrations.CreateModel(
name="post",
name='Post',
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("title", models.CharField(max_length=100)),
("content", models.TextField()),
(
"date_posted",
models.DateTimeField(default=django.utils.timezone.now),
),
(
"author",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('slug', models.SlugField(blank=True, max_length=100, unique=True)),
('content', models.TextField()),
('date_posted', models.DateTimeField(default=django.utils.timezone.now)),
('thumbnail', models.ImageField(upload_to='thumbnails')),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
18 changes: 18 additions & 0 deletions blog/migrations/0002_alter_post_content.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 4.2.10 on 2024-03-26 03:03

from django.db import migrations
import mdeditor.fields


class Migration(migrations.Migration):
dependencies = [
("blog", "0001_initial"),
]

operations = [
migrations.AlterField(
model_name="post",
name="content",
field=mdeditor.fields.MDTextField(blank=True, null=True),
),
]
19 changes: 0 additions & 19 deletions blog/migrations/0002_alter_post_id.py

This file was deleted.

10 changes: 9 additions & 1 deletion blog/models.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
from django.utils.text import slugify
from mdeditor.fields import MDTextField


# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
slug = models.SlugField(max_length=100, blank=True, unique=True)
content = MDTextField(null=True, blank=True)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
thumbnail = models.ImageField(upload_to="thumbnails")

def __str__(self):
return self.title

def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
9 changes: 9 additions & 0 deletions blog/serializer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from rest_framework import serializers

from blog.models import Post


class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = "__all__"
17 changes: 7 additions & 10 deletions blog/templates/blog/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,19 @@

<link rel="stylesheet" href="{% static 'blog/main.css' %}">
{% if title %}
<title>Django Blog - {{ title }}</title>
<title>TeaDAO Announcement - {{ title }}</title>
{% else %}
<title>Django Blog</title>
<title>TeaDAO Announcement</title>
{% endif %}
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="{% url 'blog-home' %}">Django Blog</a>
<a class="navbar-brand" href="{% url 'blog-home' %}">TeaDAO Announcement</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarText">
<ul class="navbar-nav mr-auto">
<!-- <ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="{% url 'blog-home' %}">Home <span class="sr-only">(current)</span></a>
</li>
Expand All @@ -47,11 +47,8 @@
<li class="nav-item">
<a class="nav-link" href="{% url 'register' %}">Register</a>
</li>
{% endif %}
{% endif %} -->
</ul>
<span class="navbar-text">
Created with ❀ by Akash Shrivastava
</span>
</div>
</nav>
<main role="main" class="container">
Expand All @@ -66,7 +63,7 @@
{% endif %}
{% block content %}{% endblock %}
</div>
<div class="col-md-4">
<!-- <div class="col-md-4">
<div class="content-section">
<h3>Our Sidebar</h3>
<p class='text-muted'>You can put any information here you'd like.
Expand All @@ -78,7 +75,7 @@ <h3>Our Sidebar</h3>
</ul>
</p>
</div>
</div>
</div> -->
</div>
</main>

Expand Down
2 changes: 2 additions & 0 deletions blog/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@
path("about/", views.about, name="blog-about"),
path("create-post/", views.create_post, name="create_post"),
path("detail/<int:pk>/", views.post_detail, name="detail"),
path('api/v1/blogs/', views.BlogListView.as_view()),
path('api/v1/blogs/<str:slug>/', views.BlogDetailView.as_view()),
]
28 changes: 28 additions & 0 deletions blog/views.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect, render
from rest_framework import generics, filters
from rest_framework.response import Response
from rest_framework.views import APIView

from .forms import PostForm
from .models import Post
from .serializer import PostSerializer


def home(request):
Expand Down Expand Up @@ -36,3 +41,26 @@ def create_post(request):
else:
form = PostForm()
return render(request, "blog/create_post.html", {"form": form})


class BlogListView(generics.ListAPIView):
queryset = Post.objects.all().order_by("-date_posted")
serializer_class = PostSerializer
filter_backends = [filters.SearchFilter]
search_fields = ['title', 'content'] # CÑc trường cần tìm kiếm

class BlogDetailView(APIView):
"""
Retrieve, update or delete a snippet instance.
"""

def get_object(self, slug):
try:
return Post.objects.get(slug=slug)
except Post.DoesNotExist:
raise Http404

def get(self, request, slug, format=None):
snippet = self.get_object(slug)
serializer = PostSerializer(snippet)
return Response(data=serializer.data, content_type="application/json")
Binary file removed db.sqlite3
Binary file not shown.
76 changes: 76 additions & 0 deletions django_project/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,17 @@
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"rest_framework",
"mdeditor",
"corsheaders",
]

MIDDLEWARE = [
# Uncomment the below line while deploying the app
# "whitenoise.middleware.WhiteNoiseMiddleware",
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
Expand Down Expand Up @@ -135,3 +139,75 @@
CRISPY_TEMPLATE_PACK = "bootstrap5"

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
CSRF_TRUSTED_ORIGINS = ["https://api-announcement.teadao.money"]

REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 12
}

X_FRAME_OPTIONS = 'SAMEORIGIN'

MDEDITOR_CONFIGS = {
'default': {
'width': '100% ', # Custom edit box width
'height': 700, # Custom edit box height
'toolbar': ["undo", "redo", "|",
"bold", "del", "italic", "quote", "ucwords", "uppercase", "lowercase", "|",
"h1", "h2", "h3", "h5", "h6", "|",
"list-ul", "list-ol", "hr", "|",
"link", "reference-link", "image", "code", "preformatted-text", "code-block", "table", "datetime",
"emoji", "html-entities", "pagebreak", "goto-line", "|",
"help", "info",
"||", "preview", "watch", "fullscreen"], # custom edit box toolbar
# image upload format type
'upload_image_formats': ["jpg", "jpeg", "gif", "png", "bmp", "webp", "svg"],
'image_folder': 'editor', # image save the folder name
'theme': 'default', # edit box theme, dark / default
'preview_theme': 'default', # Preview area theme, dark / default
'editor_theme': 'default', # edit area theme, pastel-on-dark / default
'toolbar_autofixed': False, # Whether the toolbar capitals
'search_replace': True, # Whether to open the search for replacement
'emoji': True, # whether to open the expression function
'tex': True, # whether to open the tex chart function
'flow_chart': True, # whether to open the flow chart function
'sequence': True, # Whether to open the sequence diagram function
'watch': True, # Live preview
'lineWrapping': True, # lineWrapping
'lineNumbers': True, # lineNumbers
'language': 'en' # zh / en / es
}
}

# enabling media uploads
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/media/'


CORS_ALLOW_HEADERS = [
"accept",
"accept-encoding",
"authorization",
"content-type",
"dnt",
"origin",
"user-agent",
"x-csrftoken",
"x-requested-with",
"baggage",
"sentry-trace",
]
CORS_ALLOW_CREDENTIALS = True

if DEBUG:
CORS_ALLOW_ALL_ORIGINS = True

CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
"https://announcement.teadao.money",
]

CORS_ALLOWED_ORIGIN_REGEXES = [
"http://localhost:3000",
"https://announcement.teadao.money",
]
1 change: 1 addition & 0 deletions django_project/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
name="logout",
),
path("", include("blog.urls")),
path("mdeditor/", include("mdeditor.urls")),
]

if settings.DEBUG:
Expand Down
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ services:
volumes:
- .:/blog_app
ports:
- 8000:8000
- 8888:8000
image: blog_app:django
container_name: blog_app
command:
Expand Down
4 changes: 4 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,7 @@ Pillow==10.2.0
crispy-bootstrap5==0.7
gunicorn==20.1.0
whitenoise==6.4.0
djangorestframework
django-filter
django-mdeditor
django-cors-headers