Skip to content
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

"Added Login & Registration | User Identification | Admin-Only Accessible Features | plus more... #33

Open
wants to merge 2 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
5 changes: 4 additions & 1 deletion blog/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,7 @@
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ("name", "email", "body")
fields = ( "name","email", "body")

name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder': "enter your first name"}))
email = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder': "Email"}))
3 changes: 2 additions & 1 deletion blog/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from django.contrib.auth.models import User
from django.db import models
from django.conf import settings

STATUS = ((0, "Draft"), (1, "Publish"))

Expand All @@ -8,7 +9,7 @@ class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="blog_posts"
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="blog_posts"
)
updated_on = models.DateTimeField(auto_now=True)
content = models.TextField()
Expand Down
2 changes: 2 additions & 0 deletions blog/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from . import views
from .feeds import AtomSiteNewsFeed, LatestPostsFeed

app_name = 'blog'

urlpatterns = [
path("feed/rss", LatestPostsFeed(), name="post_feed"),
path("feed/atom", AtomSiteNewsFeed()),
Expand Down
28 changes: 20 additions & 8 deletions blog/views.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from django.shortcuts import get_object_or_404, render
from django.shortcuts import get_object_or_404, render, redirect
from django.views import generic
from django.contrib.auth.decorators import login_required

from .forms import CommentForm
from .models import Post



class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by("-created_on")
template_name = "index.html"
Expand All @@ -21,17 +23,26 @@ def post_detail(request, slug):
post = get_object_or_404(Post, slug=slug)
comments = post.comments.filter(active=True).order_by("-created_on")
new_comment = None
# Comment posted

if request.method == "POST":
comment_form = CommentForm(data=request.POST)

if comment_form.is_valid():
user = request.user # Get the logged-in user

# Check if the provided first_name and email match the logged-in user's data
if (
user.first_name == comment_form.cleaned_data['name']
and user.email == comment_form.cleaned_data['email']
):
new_comment = 'success' # Comment successfully created
comment = comment_form.save(commit=False)
comment.post = post
comment.save()
else:
# Provided first_name or email do not match the logged-in user's data
new_comment = 'mismatch'

# Create Comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()

Expand All @@ -45,3 +56,4 @@ def post_detail(request, slug):
"comment_form": comment_form,
},
)

6 changes: 6 additions & 0 deletions mysite/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"blog",
"crispy_forms",
"django_summernote",
'users',
]


Expand Down Expand Up @@ -158,3 +159,8 @@

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
X_FRAME_OPTIONS = "SAMEORIGIN"

AUTH_USER_MODEL = "users.CustomUser"

LOGIN_REDIRECT_URL = "blog:home"
LOGOUT_REDIRECT_URL = "blog:home"
4 changes: 4 additions & 0 deletions mysite/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@
path("summernote/", include("django_summernote.urls")),
path('__debug__/', include(debug_toolbar.urls)),
path("sitemap.xml", sitemap, {"sitemaps": sitemaps}, name="sitemap"),

#redirect user to logins system
path("users/", include("users.urls")),
path("users/", include("django.contrib.auth.urls")),
]

if settings.DEBUG:
Expand Down
37 changes: 33 additions & 4 deletions templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-light bg-light shadow" id="mainNav">
<div class="container-fluid">
<a class="navbar-brand" href="{% url 'home' %}">Django central</a>
<a class="navbar-brand" href="{% url 'blog:home' %}">Django central</a>
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse"
data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false"
aria-label="Toggle navigation">
Expand All @@ -34,15 +34,39 @@
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">



{% if user.is_authenticated %}
<li class="nav-item text-black">
<a class="nav-link text-black font-weight-bold" href="#">About</a>
<a class="nav-link text-black font-weight-bold" >User: {{ user.first_name }}</a>
</li>
<li class="nav-item text-black">
<a class="nav-link text-black font-weight-bold" href="#">Policy</a>
<a class="nav-link text-black font-weight-bold" href="{% url 'users:logout' %}">Logout</a>
</li>
{% if user.is_superuser %}
<li class="nav-item text-black">
<a class="nav-link text-black font-weight-bold" href="#">Contact</a>
<a class="nav-link text-black font-weight-bold" href="admin">AdminPanel</a>
</li>
{% endif %}

{% else %}
<li class="nav-item text-black">
<a class="nav-link text-black font-weight-bold" href="{% url 'users:signup' %}" onclick="replaceURL('/users/login/'); return false;">Login</a>
</li>
<li class="nav-item text-black">
<a class="nav-link text-black font-weight-bold" href="{% url 'users:signup' %}">Register</a>
</li>
{% endif %}
<li class="nav-item text-black">
<a class="nav-link text-black font-weight-bold" href="#">About</a>
</li>
<li class="nav-item text-black">
<a class="nav-link text-black font-weight-bold" href="#">Policy</a>
</li>
<li class="nav-item text-black">
<a class="nav-link text-black font-weight-bold" href="#">Contact</a>
</li>

</ul>
</div>
</div>
Expand All @@ -68,6 +92,11 @@
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous">
</script>
<script>
function replaceURL(newURL) {
window.location.href = newURL;
}
</script>
</body>


Expand Down
5 changes: 3 additions & 2 deletions templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
<div class="row">
<div class=" col-md-8 col-md-10 mx-auto">
<div class="site-heading">
<h3 class=" site-heading my-4 mt-3 text-white"> Welcome to my awesome Blog </h3>

<h3 class=" site-heading my-4 mt-3 text-white">Welcome to my awesome Blog </h3>
<p class="text-light">We Love Django As much as you do &nbsp
</p>
</div>
Expand All @@ -31,7 +32,7 @@ <h2 class="card-title">{{ post.title }}</h2>
<p class="card-text text-muted h6">{{ post.author }} | {{ post.created_on}} </p>

<p class="card-text">{{post.content|safe|slice:":200" }}</p>
<a href="{% url 'post_detail' post.slug %}" class="btn btn-primary">Read More &rarr;</a>
<a href="{% url 'blog:post_detail' post.slug %}" class="btn btn-primary">Read More &rarr;</a>
</div>

</div>
Expand Down
32 changes: 20 additions & 12 deletions templates/post_detail.html
Original file line number Diff line number Diff line change
Expand Up @@ -35,22 +35,30 @@ <h2>{{ total_comments }} comments</h2>
{% endfor %}
</div>
</div>
<div class="col-md-8 card mb-4 mt-3 ">
{% if user.is_authenticated %}
<div class="col-md-8 card mb-4 mt-3">
<div class="card-body">
{% if new_comment %}
<div class="alert alert-success" role="alert">
Your comment is awaiting moderation
</div>
{% else %}
<h3>Leave a comment</h3>
<form method="post" style="margin-top: 1.3em;">
{{ comment_form | crispy }}
{% csrf_token %}
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</form>
{% if new_comment == 'success' %}
<div class="alert alert-success" role="alert">
Your comment is awaiting moderation
</div>
{% elif new_comment == 'mismatch' %}
<div class="alert alert-danger" role="alert">
Your username or email is wrong, please try again.
</div>
{% endif %}
<h3>Leave a comment</h3>
<form method="post" style="margin-top: 1.3em;">
{{ comment_form | crispy }}
{% csrf_token %}
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</form>
</div>
</div>



{% endif %}
</div>
</div>

Expand Down
22 changes: 22 additions & 0 deletions templates/registration/login.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{% extends "base.html" %}

{% block content %}
<div class="blank" id="first"></div>
<div class="container">
<center>
<h2>Sign In</h2>
</center>
<form method="post">
<hr>
{% csrf_token %}
{{ form.as_p }}
<hr>
<center>
<button type="submit" class="btn btn-primary">Sign In</button>
</center>
<p>New User?<a id="signin" href="{% url 'users:signup' %}"> Sign Up / Register</a></p>
</form>
</div>
<div class="blank"></div>
<div class="blank"></div>
{%endblock%}
22 changes: 22 additions & 0 deletions templates/signup.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{% extends "base.html" %}

{% block content %}
<div class="blank" id="first"></div>
<div class="container">
<center>
<h2>Sign Up</h2>
</center>

<form method="post">
<hr>
{% csrf_token %}
{{ form.as_p }}
<hr>
<center><button type="submit" class="btn btn-primary">Sign Up</button>
</center>
<p>Old User?<a id="signin" href="{% url 'users:signup' %}" onclick="replaceURL('/users/login/'); return false;"> Sign In / Login</a></p>
</form>
</div>
<div class="blank"></div>
<div class="blank"></div>
{%endblock%}
Empty file added users/__init__.py
Empty file.
40 changes: 40 additions & 0 deletions users/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser

# Define a custom admin class for the CustomUser model
class CustomUserAdmin(UserAdmin):
# Use the CustomUserCreationForm for adding users
add_form = CustomUserCreationForm
# Use the CustomUserChangeForm for editing users
form = CustomUserChangeForm
# Use the CustomUser model for managing users
model = CustomUser
# Display these fields in the list view of admin
list_display = ("email", "is_staff", "is_active",)
# Add filters for these fields in the list view
list_filter = ("email", "is_staff", "is_active",)
# Define the fieldsets for editing user details
fieldsets = (
(None, {"fields": ("email", "password")}),
("Permissions", {"fields": ("is_staff", "is_active", "groups", "user_permissions")}),
)
# Define the fieldsets for adding users
add_fieldsets = (
(None, {
"classes": ("wide",),
"fields": (
"email", "password1", "password2", "is_staff",
"is_active", "groups", "user_permissions"
)}
),
)
# Enable searching users by email
search_fields = ("email",)
# Set the default ordering for the list view
ordering = ("email",)

# Register the CustomUser model with the CustomUserAdmin
admin.site.register(CustomUser, CustomUserAdmin)
6 changes: 6 additions & 0 deletions users/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class UsersConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'users'
35 changes: 35 additions & 0 deletions users/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.forms import AuthenticationForm
from .models import CustomUser
from django import forms

# Custom form for creating new users, inheriting from UserCreationForm
class CustomUserCreationForm(UserCreationForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for visible in self.visible_fields():
visible.field.widget.attrs['class'] = 'form-control'

class Meta:
model = CustomUser
# Specify the fields to be displayed and filled in the form
fields = ("email", "first_name", "last_name")
# Add placeholder attributes for the email input field
widgets = {
'email': forms.EmailInput(attrs={'placeholder': "Email address"}),
}

# Define individual form fields with placeholder attributes
email = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder': "Email"}))
last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder': "Last name"}))

# Custom form for editing user details, inheriting from UserChangeForm
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
# Specify the fields to be displayed and edited in the form
fields = ("email",)

class CustomAuthenticationForm(AuthenticationForm):
username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control'}))
Loading