<repo_name>8264044685/user-managemant<file_sep>/pages/urls.py
from django.urls import path, include
from . import views
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('',views.index,name= 'index'),
    path('welcome',views.welcome,name= 'welcome'),
    path('show_data',views.show_data,name= 'show_data'),

] + static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)

<file_sep>/login/urls.py
from django.conf.urls import url
from django.urls import path, re_path
from . import views
from django.conf.urls.static import static
from django.conf import settings
from django.contrib.auth import views as auth_views
from login.form import EmailValidationOnForgotPassword
from django.contrib.auth.forms import PasswordResetForm
from django.contrib.auth.models import User

urlpatterns = [
                  re_path(r'^logins?/$', views.login, name='login'),
                  re_path(r'^signup/$', views.signup, name='signup'),
                  path('logout', views.logout_view, name='logout'),
                  path('password_reset/',
                       auth_views.PasswordResetView.as_view(form_class=EmailValidationOnForgotPassword),
                       name='password_reset'),
                  path('pasword-reset/done/',
                       auth_views.PasswordResetDoneView.as_view(template_name='login/password_reset_done.html'),
                       {'password_reset_form': EmailValidationOnForgotPassword}, name='password_reset_done'),
                  path('pasword-reset-confirm/<uidb64>/<token>',
                       auth_views.PasswordResetConfirmView.as_view(template_name='login/password_reset_confirm.html'),
                       name='password_reset_confirm'),
                  path('pasword-reset-complete/',
                       auth_views.PasswordResetCompleteView.as_view(template_name='login/password_reset_complete.html'),
                       name='password_reset_complete'),
                  path('pasword-change/',
                       auth_views.PasswordChangeView.as_view(template_name='login/password_change.html'),
                       name='password_chane'),
                  path('pasword-change/done/',
                       auth_views.PasswordChangeDoneView.as_view(template_name='login/password_change_done.html'),
                       name='password_change_done'),

              ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
<file_sep>/comments/views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, HttpResponse
from comments.models import post, comment, like
from django.contrib import messages
from login.models import userProfile

from django.contrib.auth.models import User, auth


@login_required(login_url='/login/login')
def create_post(request):
    print("hello")
    images = request.FILES.get('image')
    if request.method == 'POST':
        comments = []
        user_id = request.user.id
        content = request.POST['comment']
        posts = post.objects.create(user_id=user_id, image=images, content=content, comments=comments)
        posts.save()
        messages.success(request, "Your post created successfully")
        return redirect('welcome')
    else:
        return render(request, 'comments/create_post.html')
    return render(request, 'comments/create_post.html')


@login_required(login_url='/login/login')
def Show_user_post(request):
    user_id = request.user.id
    data = post.objects.filter(user_id=user_id)
    context = {'post_data': data}
    return render(request, 'comments/Show_user_post.html', context)


@login_required(login_url='/login/login')
def user_comment(request):
    if request.method == 'POST':
        user_comment = request.POST['user_comment']
        user_id = request.user.id
        post_id = request.POST['post_id']
        likes = []
        comments_data = comment.objects.create(user_id=user_id, messages=user_comment, likes=likes)
        commentlist = []
        postOldDetails = post.objects.filter(id=post_id).all()
        for pd in postOldDetails:
            for c in pd.comments:
                commentlist.append(c)
        commentlist.append(comments_data)
        postDetails = post.objects.get(id=post_id)
        postDetails.comments = commentlist
        postDetails.save()
        data = post.objects.filter(user_id=user_id)
        context = {'post_data': data}
        return redirect('welcome')
    else:
        return redirect('Show_user_post')
        return render(request, 'comments/Show_user_post.html')


@login_required(login_url='/login/login')
def show_post_comment(request):
    post_id = request.GET.get('id')
    post_comment_detail = post.objects.get(id=post_id)
    return render(request, 'comments/show_post_comment.html',
                  {'post_comment_detail': post_comment_detail, 'post_id': post_id})


@login_required(login_url='/login/login')
def comment_like(request):
    if request.method == 'POST':
        user_id = request.user.id
        comment_id = request.POST['comment_id']
        post_id = request.POST['post_id']
        if post.objects.filter(id=post_id).exists():
            postData = post.objects.get(id=post_id)
            postComments = postData.comments
            for i in range(0, len(postComments)):
                if int(comment_id) == postComments[i].comment_id:
                    if like.objects.filter(user=user_id, comment_id=int(comment_id)).exists():
                        for comment_data in postComments:
                            if comment_data.comment_id == int(comment_id):
                                for like_data in comment_data.likes:
                                    if like_data.user.id == int(user_id):
                                        comment_data.likes.pop(comment_data.likes.index(like_data))

                        postData.save()
                        likeData = like.objects.get(user=user_id, comment_id=int(comment_id))
                        likeData.delete()

                        comment_update = comment.objects.filter(comment_id=comment_id)
                        for data in comment_update:
                            comment_id = data.comment_id
                            no_of_like = data.no_of_like
                        DEFAULT_VALUE = 0
                        if no_of_like is None:
                            no_of_like = DEFAULT_VALUE

                       	no_of_like = no_of_like - 1
                        comment.objects.filter(comment_id=comment_id).update(no_of_like=no_of_like)

                        return HttpResponse(str(no_of_like))

                    else:
                        userObj = User.objects.get(id=user_id)
                        comment_update = comment.objects.filter(comment_id=comment_id)
                        for data in comment_update:
                            comment_id = data.comment_id
                            no_of_like = data.no_of_like
                        DEFAULT_VALUE = 0
                        if no_of_like is None:
                            no_of_like = DEFAULT_VALUE
                        no_of_like = no_of_like + 1
                        comment.objects.filter(comment_id=comment_id).update(no_of_like=no_of_like)

                        lokeObj = like.objects.create(user=userObj, comment_id=comment_id)
                        likelist = []
                        postData.comments[i].likes = [lokeObj]
                        postData.save()
                        return HttpResponse(str(no_of_like))


def like_show(request):
    post_id = request.GET.get('post_id')
    like_data = like.objects.filter(post_id=post_id).order_by('-id')[:5]
    return render(request, 'comments/like_show.html', {'likes': like_data})
<file_sep>/login/models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
# from .validation import validate_file_extension
from django.forms import ValidationError
from django.core.validators import RegexValidator
from django.core.validators import MaxValueValidator


class userProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    address = models.TextField(blank=True)

    mobile_no = models.BigIntegerField(primary_key=True, validators=[MaxValueValidator(9999999999)])

    city = models.CharField(max_length=50)
    state = models.CharField(max_length=50)
    country = models.CharField(max_length=50)
    profilePicture = models.ImageField(upload_to='photos/%Y/%m/%d')

    def clean_profilePicture(self):
        image_file = self.cleaned_data.get('profilePicture')
        if not image_file.name.endswith(".jpg", ".jpeg", ".png"):
            raise ValidationError("Only .jpg, .jpeg, .png image accepted")
        return image_file

    def __str__(self):
        return self.user.username
<file_sep>/login/form.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import *
from django.core.exceptions import ValidationError
from django.contrib.auth.forms import PasswordResetForm
class SignUpForm(UserCreationForm):
    username = forms.CharField(label='Enter Username', min_length=4, max_length=150)
    email = forms.EmailField(label='Enter email')
    password1 = forms.CharField(label='Enter password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput)


    class Meta:
        model = User
        fields= ('username','email','password1','password2')

    # def clean_email(self):
    #         username = self.cleaned_data["username"]
    #         email = self.cleaned_data["email"]
    #         users = User.objects.filter(email__iexact=email).exclude(username__iexact=username)
    #         if users:
    #             raise forms.ValidationError(("User with that email already exists."))
    #         return email.lower()

    def clean_username(self):
        username = self.cleaned_data['username'].lower()
        r = User.objects.filter(username=username)
        if r.count():
            raise  ValidationError("Username already exists")
        return username
 
    def clean_email(self):
        email = self.cleaned_data['email'].lower()
        r = User.objects.filter(email=email)
        if r.count():
            raise  ValidationError("Email already exists")
        return email
 
    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
 
        if password1 and password2 and password1 != password2:
            raise ValidationError("Password don't match")
 
        return password2
 
    def save(self, commit=True):
        user = User.objects.create_user(
            self.cleaned_data['username'],
            self.cleaned_data['email'],
            self.cleaned_data['password1']
        )
        return user
    

        
class ProfileForm(forms.ModelForm):
    profilePicture = models.ImageField(upload_to = 'photos/%Y/%m/%d', blank = True)



    class Meta:
        model = userProfile
        fields = ('address','mobile_no','city','state','country','profilePicture')


# class AccountAuthenticationForm(forms.ModelForm):

#     password = forms.CharField(label='Password', widget=forms.PasswordInput)

#     class Meta:
#         model = User
#         fields = ('username', 'password')

#     def clean(self):
#         if self.is_valid():
#             email = self.cleaned_data['email']
#             password = self.cleaned_data['password']
#             if not authenticate(email=email, password=password):
#                 raise forms.ValidationError("Invalid login")


class EmailValidationOnForgotPassword(PasswordResetForm):
    def clean_email(self):
        email = self.cleaned_data['email']
        if not User.objects.filter(email__iexact=email, is_active=True).exists():
            msg = ("There is no user registered with the specified E-Mail address.")

            self.add_error('email', msg)
        return email<file_sep>/pages/views.py
from django.shortcuts import render
from login.models import userProfile
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from comments.models import post, like
from django.contrib import messages


# Create your views here.
def index(request):
    return render(request, 'pages/index.html')


# welcome method like Dashboard
@login_required(login_url='/login/login')
def welcome(request):
    user_id = request.user.id
    posts = post.objects.select_related('user', )
    context = {'posts': posts, 'user_id': user_id}
    return render(request, 'pages/welcome.html', context)


# show all the User data
@login_required(login_url='/login/login')
def show_data(request):
    users = User.objects.all().select_related('userprofile')
    print(users.query)
    context = {
        'userData': users,
    }
    return render(request, 'pages/show_data.html', context)
<file_sep>/comments/urls.py
from django.urls import path, re_path
from django.conf.urls.static import static
from django.conf import settings
from . import views

urlpatterns = [
                  re_path(r'^create_post?/$', views.create_post, name='create_post'),
                  path('Show_user_post', views.Show_user_post, name='Show_user_post'),
                  path('user_comment', views.user_comment, name='user_comment'),
                  path('show_post_comment', views.show_post_comment, name='show_post_comment'),
                  path('comment_like', views.comment_like, name='comment_like'),
                  path('like_show', views.like_show, name='like_show')
              ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
<file_sep>/comments/models.py
from django.db import models
from django.conf import settings
from .validation import validate_content
from djongo.models import ArrayModelField
from django.contrib.auth.models import User
from django.utils import timezone
from djongo import models
from datetime import datetime


# Create your models here.

#

class like(models.Model):
    comment_id = models.IntegerField(blank=True, null=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)


class comment(models.Model):
    def ids():
        no = comment.objects.count()
        if no == None:
            return 1
        else:
            return no + 1

    comment_id = models.IntegerField(default=ids, unique=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    messages = models.CharField(max_length=140, blank=True)
    time = models.DateTimeField(auto_now=True)
    no_of_like = models.IntegerField(blank=True)
    likes = ArrayModelField(model_container=like, null=True, blank=True)

    def __str__(self):
        return self.messages


class post(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True)
    content = models.CharField(max_length=140, validators=[validate_content], blank=True)
    updated = models.DateTimeField(default=datetime.now, blank=True)
    timestamp = models.DateTimeField(default=datetime.now, blank=True)
    comments = ArrayModelField(model_container=comment, null=True, blank=True)

    def __str__(self):
        return self.user.username
<file_sep>/comments/admin.py
from django.contrib import admin
from comments.models import post
from comments.models import comment

# Register your models here.
class posts(admin.ModelAdmin):
    list_display = ['id','content','image','comments']

class comments(admin.ModelAdmin):
    list_display = ['comment_id','messages','no_of_like']
    list_editable = ['messages',]
    list_per_page = 10

admin.site.register(post,posts)
admin.site.register(comment,comments)



<file_sep>/comments/migrations/0001_initial.py
# Generated by Django 2.2 on 2020-02-04 11:24

import comments.models
import comments.validation
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import djongo.models.fields


class Migration(migrations.Migration):

    initial = True

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

    operations = [
        migrations.CreateModel(
            name='post',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('image', models.ImageField(blank=True, upload_to='photos/%Y/%m/%d')),
                ('content', models.CharField(blank=True, max_length=140, validators=[comments.validation.validate_content])),
                ('updated', models.DateTimeField(blank=True, default=datetime.datetime.now)),
                ('timestamp', models.DateTimeField(blank=True, default=datetime.datetime.now)),
                ('comments', djongo.models.fields.ArrayModelField(blank=True, model_container=comments.models.comment, null=True)),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='comment',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('comment_id', models.IntegerField(default=comments.models.comment.ids, unique=True)),
                ('messages', models.CharField(blank=True, max_length=140)),
                ('time', models.DateTimeField(auto_now=True)),
                ('no_of_like', models.IntegerField(blank=True)),
                ('likes', djongo.models.fields.ArrayModelField(blank=True, model_container=comments.models.like, null=True)),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
        ),
    ]
<file_sep>/login/views.py
from django.shortcuts import render, redirect, Http404
from django.core.mail import send_mail
from django.conf import settings
# from .form import SignUpForm
from .form import SignUpForm, ProfileForm
from django.contrib.auth.models import auth
from django.core.files.storage import FileSystemStorage
from django.contrib.auth import login, authenticate, logout
from django.contrib import messages
from django.contrib.auth.models import User
from django.views.decorators.cache import cache_control
from django.contrib.auth.tokens import default_token_generator
from django.template.loader import render_to_string


def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        profileForm = ProfileForm(request.POST, request.FILES)

        if form.is_valid() and profileForm.is_valid():
            print("success")
            user = form.save()
            profile = profileForm.save(commit=False)
            profile.user = user
            profile.save()

            return redirect('login')
        else:
            # messages.error(request,'Wrong Input')
            return render(request, 'login/signup.html', {'form': form, 'userProfileForm': profileForm})
    else:
        profileForm = ProfileForm()
        form = SignUpForm()
        # context = {'form': profileForm}
        context = {'form': form, 'userProfileForm': profileForm, }
        return render(request, 'login/signup.html', context)
    return render(request, 'login/signup.html', {'form': form, 'userProfileForm': profileForm})


def login(request):
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['<PASSWORD>']
        user = auth.authenticate(username=username, password=password)

        if user is not None:
            auth.login(request, user)
            messages.success(request, "You are login successfully")
            return redirect('welcome')
        else:
            messages.warning(request, "Username and password are not match")
            return redirect('login')
    else:
        if request.user.is_authenticated:
            return redirect('/')
        else:
            return render(request, 'login/login.html')

@cache_control(no_cache=True, must_revalidate=True, no_store=True)
def logout_view(request):
    auth.logout(request)
    return render(request, 'pages/index.html')


def reset_password_view(request):
    if request.method == 'POST':
        email = request.POST['email']
        admin_email = '<EMAIL>'

        if email == None or email == "":
            messages.error(request, email)
            return redirect('reset_password')
        else:
            if User.objects.filter(email=email).exists():
                send_mail(
                    'This mail for reset password',
                    'just Click Below link to reset password',
                    'Thank you for using our services.'
                    '<EMAIL>',
                    [admin_email, email],
                    fail_silently=False
                )
                messages.success(request, "Check your E-mail to  reset password : " + email)
                return redirect('reset_password')
            else:
                messages.error(request, "Entered email is not match  : " + email)
                return redirect('reset_password')
    else:
        # messages.info(request, "Please enter email")
        return render(request, 'login/reset_password.html')
