Project
settings.py
settings.py
# custom code
import os
from pathlib import Path
from django.contrib.messages import constants as messages
# custom code
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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',
],
},
},
]
# custom code
TIME_ZONE = 'Asia/Dhaka'
# custom code
STATIC_URL = '/static/'
MEDIA_URL = '/images/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env')]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
MESSAGE_TAGS = {
messages.ERROR:'danger'
}
# custom code
# CKEDITOR_UPLOAD_PATH = "/home/static/media"
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'full',
'extraPlugins': ','.join(
[
'codesnippet',
]),
},
}
CKEDITOR_CONFIGS = {
'default': {
'skin': 'moono',
# 'skin': 'office2013',
'toolbar_Basic': [
['Source', '-', 'Bold', 'Italic']
],
'toolbar_YourCustomToolbarConfig': [
{'name': 'document', 'items': ['Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates']},
{'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']},
{'name': 'editing', 'items': ['Find', 'Replace', '-', 'SelectAll']},
{'name': 'forms',
'items': ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',
'HiddenField']},
'/',
{'name': 'basicstyles',
'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']},
{'name': 'paragraph',
'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-',
'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl',
'Language']},
{'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']},
{'name': 'insert',
'items': ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe']},
'/',
{'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']},
{'name': 'colors', 'items': ['TextColor', 'BGColor']},
{'name': 'tools', 'items': ['Maximize', 'ShowBlocks']},
{'name': 'about', 'items': ['About']},
'/', # put this to force next toolbar on new line
{'name': 'extra', 'items': [ 'CodeSnippet',
# put the name of your editor.ui.addButton here
'Preview',
'Maximize',
]},
],
'toolbar': 'YourCustomToolbarConfig', # put selected toolbar config here
# 'toolbarGroups': [{ 'name': 'document', 'groups': [ 'mode', 'document', 'doctools' ] }],
# 'height': 291,
# 'width': '100%',
# 'filebrowserWindowHeight': 725,
# 'filebrowserWindowWidth': 940,
# 'toolbarCanCollapse': True,
# 'mathJaxLib': '//cdn.mathjax.org/mathjax/2.2-latest/MathJax.js?config=TeX-AMS_HTML',
'tabSpaces': 4,
'extraPlugins': ','.join([
'uploadimage', # the upload image feature
# your extra plugins here
'div',
'autolink',
'autoembed',
'embedsemantic',
'autogrow',
# 'devtools',
'widget',
'lineutils',
'clipboard',
'dialog',
'dialogui',
'elementspath',
'codesnippet',
'sourcedialog',
'templates',
'widget',
'wsc',
'sharedspace',
'mathjax',
'embedbase',
'docprops',
'magicline',
'stylesheetparser',
]),
}
}
urls.py
"""webapp 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, include
from django.conf.urls.static import static
from django.conf import settings
# admin.site.site_header = 'pyCoder Admin'
# admin.site.site_title = 'pyCoder Admin Panel'
admin.site.index_title = 'Welcome to Web App Panel'
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('home.urls')),
path('blog/', include('blog.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Home app
Views.py
from django.shortcuts import render, HttpResponse, redirect
from marketing.models import *
from blog.models import Post
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.http.response import HttpResponse
def home(request):
allPosts= Post.objects.all()
featured = Post.objects.filter(featured=True)
slider = Post.objects.filter(slider=True).order_by('-timestamp')
latest = Post.objects.order_by('-timestamp')[0:3]
most_recent = Post.objects.order_by('-timestamp')[:5]
galary = Post.objects.order_by('-timestamp')[:4]
# slide = Carausel.objects.all()
# slide_featured = Carausel.objects.filter(featured=True)
if request.method=="POST":
email=request.POST['email']
if len(email)<3: a="" about.html="" about="" allposts="" already="" been="" contact.html="" contact.save="" contact="Contact(name=name," content="content)" context="" correctly="" def="" else:="" email="email," featured="" fill="" form="" fully="" galary="" has="" have="" home="" if="" index.html="" latest="" lease="" len="" message="" messages.error="" messages.success="" most_recent="" name="" new="" object_list="" one="" or="" ou="" our="" phone="phone," please="" query="" redirect="" render="" request.method="=" request="" return="" search="" sent="" signup.save="" signup="Signup(email=email)" slider="" sliders="" subscribe="" subscribed="" success="" successfully="" the="" try="" type="" user.objects.filter="" valid="" with="">78:
allPosts=Post.objects.none()
else:
allPostsTitle= Post.objects.filter(title__icontains=query)
allPostsAuthor= Post.objects.filter(author__icontains=query)
allPostsContent =Post.objects.filter(content__icontains=query)
allPosts= allPostsTitle.union(allPostsContent, allPostsAuthor)
if allPosts.count()==0:
messages.warning(request, "No search results found. Please refine your query.")
params={
'allPosts': allPosts,
'query': query
}
return render(request, "home/search_results.html", params)
def handleSignUp(request):
if request.method=="POST":
# Get the post parameters
username=request.POST['username']
email=request.POST['email']
fname=request.POST['fname']
lname=request.POST['lname']
pass1=request.POST['pass1']
pass2=request.POST['pass2']
# check for errorneous input
if len(username)<10: -="" 10="" account="" again="" already="" and="" be="" been="" characters="" code="" contain="" create="" created="" credentials="" def="" do="" else:="" email="" found="" get="" handellogout="" handelogin="" has="" his="" home="" httpresponse="" if="" in="" is="" letters="" logged="" login="" loginpassword="" loginusername="" logout="" match="" messages.error="" messages.success="" must="" myuser.first_name="fname" myuser.last_name="lname" myuser.save="" myuser="User.objects.create_user(username," name="" none:="" not="" numbers="" nvalid="" only="" out="" parameters="" pass1="" pass2="" password="loginpassword)" passwords="" please="" post="" redirect="" request.method="=" request="" return="" should="" successfully="" taken="" the="" try="" uccessfully="" under="" user.objects.filter="" user="" username.isalnum="" username="" your="">10:>3:>
urls.py
from django import views
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('about', views.about, name="about"),
path('contact', views.contact, name="contact"),
path('search', views.search, name='search'),
path('signup', views.handleSignUp, name="handleSignUp"),
path('login', views.handeLogin, name="handleLogin"),
path('logout', views.handelLogout, name="handleLogout"),
]
models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils.timezone import now
class Contact(models.Model):
sno= models.AutoField(primary_key=True)
name= models.CharField(max_length=255)
phone= models.CharField(max_length=13)
email= models.CharField(max_length=100)
content= models.TextField()
timeStamp=models.DateTimeField(auto_now_add=True, blank=True)
def __str__(self):
return "Message from " + self.name + ' - ' + self.email
admin.py
from django.contrib import admin
from .models import *
admin.site.register(Contact)
Blog App
views.py
from django.shortcuts import render, HttpResponse, redirect
from blog.models import Post, BlogComment
from django.contrib import messages
from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage
def blogHome(request):
post_list = Post.objects.all()
most_recent = Post.objects.order_by('-timestamp')[:5]
paginator = Paginator(post_list, 8)
#page = request.GET.get('page')
page_request_var = 'page'
page = request.GET.get(page_request_var)
try:
allPosts = paginator.page(page)
except PageNotAnInteger:
allPosts = paginator.page(1)
except EmptyPage:
allPosts = paginator.page(paginator.num_pages)
context={
'allPosts': allPosts,
'most_recent': most_recent,
'page_request_var': page_request_var,
}
return render(request, "blog/blogHome.html", context)
def blogPost(request, slug):
post=Post.objects.filter(slug=slug).first()
most_recent = Post.objects.order_by('-timestamp')[:5]
comments= BlogComment.objects.filter(post=post).order_by('-timestamp')
context={'post':post, 'comments': comments, 'most_recent': most_recent}
return render(request, "blog/blogPost.html", context)
def postComment(request):
if request.method == "POST":
comment=request.POST.get('comment')
user=request.user
postSno =request.POST.get('postSno')
post= Post.objects.get(sno=postSno)
comment=BlogComment(comment= comment, user=user, post=post)
comment.save()
messages.success(request, "Your comment has been posted successfully")
return redirect(f"/blog/{post.slug}")
urls.py
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('postComment', views.postComment, name="postComment"),
path('', views.blogHome, name="bloghome"),
path('', views.blogPost, name="blogPost"),
#path('postComment', views.postComment, name="postComment")
]
models.py
from django.db import models
from ckeditor.fields import RichTextField
from django.contrib.auth.models import User
from django.utils.timezone import now
# class IpMoodel(models.Model):
# ip = models.CharField(max_length=100)
# def __str__(self):
# return self.ip
class Post(models.Model):
title = models.CharField(max_length=100)
overview = models.TextField()
slug = models.SlugField(max_length=100, blank=True, null=True)
timestamp = models.DateTimeField(auto_now_add=True)
content = RichTextField()
# comment_count = models.IntegerField(default = 0)
# view_count = models.IntegerField(default = 0)
author=models.CharField(max_length=20)
author_pic = models.ImageField(null=True, blank=True)
thumbnail = models.ImageField()
featured = models.BooleanField()
slider = models.BooleanField(null=True, blank=True)
# views = models.ManyToManyField(IpMoodel, related_name="post_views", blank=True)
def __str__(self):
return self.title + " by " + self.author
class BlogComment(models.Model):
sno= models.AutoField(primary_key=True)
comment=models.TextField()
user=models.ForeignKey(User, on_delete=models.CASCADE)
post=models.ForeignKey(Post, on_delete=models.CASCADE)
parent=models.ForeignKey('self',on_delete=models.CASCADE, null=True )
timestamp= models.DateTimeField(default=now)
def __str__(self):
return self.comment[0:13] + "..." + "by" + " " + self.user.username
# class Comment(models.Model):
# user = models.ForeignKey(User, on_delete=models.CASCADE)
# date = models.DateTimeField(auto_now_add=True)
# post = models.ForeignKey('Post', on_delete=models.CASCADE)
# content = models.TextField(null=True, blank=True)
# def __str__(self):
# return self.content[0:13] + "..." + "by" + " " + self.user.username
admin.py
from django.contrib import admin
from blog.models import *
admin.site.register(Post)
admin.site.register(BlogComment)
# admin.site.register(Comment)
# admin.site.register(IpMoodel)
Tags
django