User Creation Module

main
Babit Shrestha 6 months ago
parent 1e505a8a24
commit 9993f2f132
  1. BIN
      sahara/db.sqlite3
  2. BIN
      sahara/main/__pycache__/__init__.cpython-312.pyc
  3. BIN
      sahara/main/__pycache__/admin.cpython-312.pyc
  4. BIN
      sahara/main/__pycache__/apps.cpython-312.pyc
  5. BIN
      sahara/main/__pycache__/forms.cpython-312.pyc
  6. BIN
      sahara/main/__pycache__/managers.cpython-312.pyc
  7. BIN
      sahara/main/__pycache__/models.cpython-312.pyc
  8. BIN
      sahara/main/__pycache__/urls.cpython-312.pyc
  9. BIN
      sahara/main/__pycache__/views.cpython-312.pyc
  10. 5
      sahara/main/admin.py
  11. 2
      sahara/main/creds.txt
  12. 45
      sahara/main/forms.py
  13. 64
      sahara/main/migrations/0001_initial.py
  14. BIN
      sahara/main/migrations/__pycache__/0001_initial.cpython-312.pyc
  15. BIN
      sahara/main/migrations/__pycache__/0002_alter_baseuser_options_baseuser_date_joined_and_more.cpython-312.pyc
  16. BIN
      sahara/main/migrations/__pycache__/0003_remove_baseuser_role.cpython-312.pyc
  17. BIN
      sahara/main/migrations/__pycache__/0004_alter_baseuser_managers_baseuser_role.cpython-312.pyc
  18. BIN
      sahara/main/migrations/__pycache__/0005_alter_baseuser_managers.cpython-312.pyc
  19. BIN
      sahara/main/migrations/__pycache__/0006_remove_baseuser_username.cpython-312.pyc
  20. BIN
      sahara/main/migrations/__pycache__/__init__.cpython-312.pyc
  21. 41
      sahara/main/models.py
  22. 17
      sahara/main/templates/main/create_user.html
  23. 5
      sahara/main/templates/main/delete_user.html
  24. 65
      sahara/main/templates/main/mail/welcome_email.html
  25. 14
      sahara/main/templates/main/mail/welcome_email.txt
  26. 5
      sahara/main/templates/main/update_user.html
  27. 5
      sahara/main/templates/main/user_list.html
  28. 8
      sahara/main/urls.py
  29. 26
      sahara/main/utilities.py
  30. 92
      sahara/main/views.py
  31. BIN
      sahara/media/Screenshot_1.png
  32. BIN
      sahara/media/Screenshot_1_ADxCcNz.png
  33. BIN
      sahara/media/Screenshot_1_Nr3wRlz.png
  34. BIN
      sahara/media/Screenshot_1_Y0GUvRC.png
  35. BIN
      sahara/media/Screenshot_2025-01-10_182515.png
  36. BIN
      sahara/media/Screenshot_2025-01-10_182515_KdukpRJ.png
  37. BIN
      sahara/media/uploads/citizenship/Screenshot_1.png
  38. BIN
      sahara/sahara/__pycache__/__init__.cpython-312.pyc
  39. BIN
      sahara/sahara/__pycache__/settings.cpython-312.pyc
  40. BIN
      sahara/sahara/__pycache__/urls.cpython-312.pyc
  41. BIN
      sahara/sahara/__pycache__/wsgi.cpython-312.pyc
  42. 2
      sahara/sahara/asgi.py
  43. 47
      sahara/sahara/settings.py
  44. 21
      sahara/sahara/urls.py
  45. 10
      sahara/sahara/wsgi.py

Binary file not shown.

@ -1,3 +1,8 @@
from django.contrib import admin from django.contrib import admin
from .models import BaseUser,Role
# Register your models here. # Register your models here.
admin.site.register(BaseUser)
admin.site.register(Role)

@ -1,2 +0,0 @@
app_password ="duse xjaj pxkg wyur"
app_email = "dmyemail254@gmail.com"

@ -0,0 +1,45 @@
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import BaseUser
class BaseUserForm(UserCreationForm):
class Meta:
model = BaseUser
fields = [
'first_name',
'last_name',
'bio',
'address',
'contact_number',
'image',
'citizenship',
'certificate',
'price',
'role',
'email',
]
password1 = forms.CharField(
widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'}),
label='Password',
min_length=8,
)
password2 = forms.CharField(
widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Confirm Password'}),
label='Confirm Password',
min_length=8,
)
def clean_password2(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match.")
return password2
def save(self, commit=True):
user = super().save(commit=False)
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user

@ -0,0 +1,64 @@
# Generated by Django 5.1.4 on 2025-01-11 11:43
import django.contrib.auth.models
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='Role',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('role', models.CharField(max_length=20)),
('role_desc', models.TextField()),
],
),
migrations.CreateModel(
name='BaseUser',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('image', models.ImageField(blank=True, null=True, upload_to='')),
('bio', models.TextField(blank=True, null=True)),
('address', models.CharField(blank=True, max_length=50, null=True)),
('contact_number', models.CharField(blank=True, max_length=15, null=True, unique=True)),
('email', models.EmailField(max_length=254, unique=True)),
('citizenship', models.FileField(blank=True, null=True, upload_to='uploads/citizenship')),
('certificate', models.FileField(blank=True, null=True, upload_to='uploads/certificates')),
('token', models.CharField(blank=True, max_length=64, null=True)),
('is_verified', models.BooleanField(default=False)),
('price', models.DecimalField(blank=True, decimal_places=2, max_digits=9999, null=True)),
('ratings', models.IntegerField(default=1)),
('member_since', models.DateTimeField(auto_now_add=True)),
('profile_updated', models.DateTimeField(auto_now=True)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.permission', verbose_name='user permissions')),
('role', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='users', to='main.role')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]

@ -1,7 +1,10 @@
from django.db import models from django.db import models
from django.contrib.auth.models import User from django.contrib.auth.models import AbstractUser
from django.dispatch import receiver
from django.db.models.signals import post_save
# Create your models here.
class Role(models.Model): class Role(models.Model):
role = models.CharField(max_length=20) role = models.CharField(max_length=20)
@ -10,23 +13,31 @@ class Role(models.Model):
def __str__(self): def __str__(self):
return self.role return self.role
class BaseUser(AbstractUser):
class BaseUser(models.Model): username = None
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user") image = models.ImageField(null=True, blank=True)
image = models.ImageField()
bio = models.TextField(null=True, blank=True) bio = models.TextField(null=True, blank=True)
address = models.CharField(null=True, blank=True, max_length=50) address = models.CharField(null=True, blank=True, max_length=50)
contact_number = models.CharField(unique=True, max_length=15) contact_number = models.CharField(unique=True, max_length=15, null=True, blank=True)
email = models.EmailField(unique=True) email = models.EmailField(unique=True)
citizenship = models.FileField(upload_to ='uploads/citizenship') citizenship = models.FileField(upload_to='uploads/citizenship', null=True, blank=True)
certificate = models.FileField(upload_to='uploads/certificates') certificate = models.FileField(upload_to='uploads/certificates', blank=True, null=True)
is_activated = models.BooleanField(default=False) #is_activated = models.BooleanField(default=False)
token = models.CharField(max_length=64,blank=True,null=True)
is_verified = models.BooleanField(default=False) is_verified = models.BooleanField(default=False)
price = models.DecimalField(max_digits=9999,decimal_places=2) price = models.DecimalField(max_digits=9999, decimal_places=2, null=True, blank=True)
ratings = models.PositiveIntegerField() ratings = models.IntegerField(default=1)
role = models.ForeignKey(Role, on_delete=models.CASCADE, related_name="user_role") role = models.ForeignKey('Role', on_delete=models.SET_NULL, related_name="users", null=True, blank=True)
def __str__(self): member_since = models.DateTimeField(auto_now_add=True)
return self.user.username profile_updated = models.DateTimeField(auto_now=True)
USERNAME_FIELD = "email" USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["image", "contact_number", "bio", "address", "citizenship", "certificate", "price", "password"]
def __str__(self):
return self.email
@receiver(post_save, sender=AbstractUser)
def user_to_inactive(sender, instance, created, update_fields, **kwargs):
if created:
instance.is_active = False

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<title>Document</title>
</head>
<body>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Create</button>
</form>
</body>
</html>

@ -0,0 +1,5 @@
<form method="post">
{% csrf_token %}
<p>Are you sure you want to delete {{ object }}?</p>
<button type="submit">Delete</button>
</form>

@ -0,0 +1,65 @@
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome to Sahara</title>
<style>
body {
font-family: Arial, sans-serif;
color: #333;
background-color: #f7f7f7;
padding: 30px;
}
.email-container {
background-color: #ffffff;
padding: 20px;
border-radius: 8px;
max-width: 600px;
margin: 0 auto;
}
h1 {
color: #2c3e50;
}
.company-logo {
max-width: 150px;
margin-bottom: 20px;
}
.cta-button {
background-color: #3498db;
color: #ffffff;
padding: 10px 20px;
border-radius: 5px;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
.cta-button:hover {
background-color: #2980b9;
}
p {
font-size: 16px;
}
</style>
</head>
<body>
<div class="email-container">
<h1>Welcome to Sahara!</h1>
<img src="{% static 'images/sahara_logo.png' %}" alt="Sahara" class="company-logo">
<p>Hello {{ user.first_name }},</p>
<p>Thank you for signing up with Sahara! We're excited to have you on board.</p>
<p>Please click the button below to activate your account:</p>
<a href="{{ activation_link }}" class="cta-button">Activate Your Account</a>
<p>If you did not sign up for this account, please ignore this email.</p>
<p>Best regards,<br>Sahara Team</p>
</div>
</body>
</html>

@ -0,0 +1,14 @@
Welcome to Sahara!
Hello {{ user.first_name }},
Thank you for signing up with Sahara! We're excited to have you on board.
Please click the link below to activate your account:
{{ activation_link }}
If you did not sign up for this account, please ignore this email.
Best regards,
Sahara Team

@ -0,0 +1,5 @@
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Update</button>
</form>

@ -0,0 +1,5 @@
{% for user in users %}
<p><a href="{% url 'update_user' pk=user.pk %}">{{ user }}</a>
<a href="{% url 'delete_user' pk=user.pk %}">(delete)</a></p>
{% endfor %}

@ -1,7 +1,9 @@
from django.contrib import admin from django.urls import path
from django.urls import path, include from .views import homeView,send_mail_page,createUserView,activate_account
from .views import homeView
urlpatterns = [ urlpatterns = [
path('',homeView, name="home"), path('',homeView, name="home"),
path('send-email/',send_mail_page,name="sendmail"),
path('user/register/',createUserView,name="register"),
path('activate/<str:token>/', activate_account, name='activate'),
] ]

@ -0,0 +1,26 @@
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.conf import settings
from django.urls import reverse
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.tokens import default_token_generator
def send_welcome_email(user, request):
token = 'generated_token_here'
activation_link = f"{get_current_site(request).domain}{reverse('account:activate', args=[token])}"
subject = "Welcome to Sahara - Please Activate Your Account"
html_message = render_to_string('welcome_email.html', {
'user': user,
'activation_link': activation_link,
})
plain_message = strip_tags(html_message)
send_mail(
subject,
plain_message,
settings.DEFAULT_FROM_EMAIL,
[user.email],
html_message=html_message,
)

@ -1,7 +1,91 @@
from django.shortcuts import render,HttpResponse from django.shortcuts import render,redirect,HttpResponse
from django.core.mail import send_mail
from django.conf import settings
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.conf import settings
from django.urls import reverse
from django.contrib.sites.shortcuts import get_current_site
from . forms import BaseUserForm
from django.contrib import messages
from django.contrib.auth.tokens import default_token_generator
# Create your views here. # Create your views here.
from .models import BaseUser
def homeView(request): def homeView(request):
return HttpResponse("<h1>Home Page</h1>") return HttpResponse("home")
def createUserView(request):
if request.method == 'POST':
form = BaseUserForm(request.POST, request.FILES)
print(form)
if form.is_valid():
form.save()
form.is_a
#return redirect('home')
return HttpResponse("<h1>User Created</h1>")
else:
form = BaseUserForm()
return render(request, 'main/create_user.html', {
'form': form
})
def send_mail_page():
address = "sajeshmaan@gmail.com"
subject = "Congrts Team Flash"
message = "Congrts Team Flash hackx committe has announced your team as a winner"
try:
send_mail(subject, message, settings.EMAIL_HOST_USER, [address,'rajakiaryal0@gmail.com'])
result= 'Email sent successfully'
except Exception as e:
result = f'Error sending email: {e}'
def send_welcome_email(user, request):
# Generate activation link
user = BaseUser.objects.get(email="user@example.com") # Replace with your user object
token = default_token_generator.make_token(user)
token = 'generated_token_here' # This token will be generated based on your activation logic
activation_link = f"{get_current_site(request).domain}{reverse('account:activate', args=[token])}"
# Prepare email subject and message
subject = "Welcome to Sahara - Please Activate Your Account"
# Render the HTML email
html_message = render_to_string('welcome_email.html', {
'user': user,
'activation_link': activation_link,
})
# Render the plain-text version of the email
plain_message = strip_tags(html_message)
# Send the email
send_mail(
subject,
plain_message,
settings.DEFAULT_FROM_EMAIL,
[user.email],
html_message=html_message,
)
def activate_account(request, token):
try:
# Decode token and retrieve user
user = User.objects.get(email__iexact=user_email_from_token)
if user:
# Activate user account
user.is_active = True
user.save()
messages.success(request, "Account activated successfully!")
return redirect('login') # Redirect to the login page
else:
messages.error(request, "Invalid activation link.")
except Exception as e:
messages.error(request, str(e))
return redirect('home') # Redirect to homepage in case of error

Binary file not shown.

After

Width:  |  Height:  |  Size: 273 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 273 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 273 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 273 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 273 KiB

@ -4,7 +4,7 @@ ASGI config for sahara project.
It exposes the ASGI callable as a module-level variable named ``application``. It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see For more information on this file, see
https://docs.djangoproject.com/en/5.1/howto/deployment/asgi/ https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/
""" """
import os import os

@ -1,27 +1,32 @@
""" """
Django settings for sahara project. Django settings for sahara project.
Generated by 'django-admin startproject' using Django 5.1.4. Generated by 'django-admin startproject' using Django 5.0.6.
For more information on this file, see For more information on this file, see
https://docs.djangoproject.com/en/5.1/topics/settings/ https://docs.djangoproject.com/en/5.0/topics/settings/
For the full list of settings and their values, see For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.1/ref/settings/ https://docs.djangoproject.com/en/5.0/ref/settings/
""" """
from pathlib import Path from pathlib import Path
import os import os
from dotenv import load_dotenv
# Build paths inside the project like this: BASE_DIR / 'subdir'.
load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'. # Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent BASE_DIR = Path(__file__).resolve().parent.parent
import os
# Quick-start development settings - unsuitable for production # Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/ # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-^huq1^)wu+)bo*m#&l_4w6e&oi%iyn+^5%o4kt1zim(!!&an&y' SECRET_KEY = 'django-insecure-dw78ln%=0i^uy4zj78lkx=p_98ik3%h@u%wod1va651^1jyy*m'
# SECURITY WARNING: don't run with debug turned on in production! # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True DEBUG = True
@ -38,7 +43,7 @@ INSTALLED_APPS = [
'django.contrib.sessions', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.messages',
'django.contrib.staticfiles', 'django.contrib.staticfiles',
"main", 'main'
] ]
MIDDLEWARE = [ MIDDLEWARE = [
@ -71,9 +76,19 @@ TEMPLATES = [
WSGI_APPLICATION = 'sahara.wsgi.application' WSGI_APPLICATION = 'sahara.wsgi.application'
####EMAIL CONF
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = os.environ.get("EMAIL_ADDRESS")
EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_PASSWORD")
# Database # Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases # https://docs.djangoproject.com/en/5.0/ref/settings/#databases
DATABASES = { DATABASES = {
'default': { 'default': {
@ -84,7 +99,7 @@ DATABASES = {
# Password validation # Password validation
# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators # https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [ AUTH_PASSWORD_VALIDATORS = [
{ {
@ -103,7 +118,7 @@ AUTH_PASSWORD_VALIDATORS = [
# Internationalization # Internationalization
# https://docs.djangoproject.com/en/5.1/topics/i18n/ # https://docs.djangoproject.com/en/5.0/topics/i18n/
LANGUAGE_CODE = 'en-us' LANGUAGE_CODE = 'en-us'
@ -115,20 +130,20 @@ USE_TZ = True
# Static files (CSS, JavaScript, Images) # Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/ # https://docs.djangoproject.com/en/5.0/howto/static-files/
STATIC_URL = 'static/' STATIC_URL = 'static/'
# Default primary key field type # Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field # https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
AUTH_USER_MODEL = 'main.BaseUser'
STATIC_URL = '/static/' STATIC_URL = '/static/'
#STATICFILES_DIRS = [BASE_DIR / "static"] #STATICFILES_DIRS = [BASE_DIR / "static"]
STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_ROOT = BASE_DIR / "media"

@ -1,23 +1,12 @@
"""
URL configuration for sahara project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/5.1/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.contrib import admin
from django.urls import path,include from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [ urlpatterns = [
path('admin/', admin.site.urls), path('admin/', admin.site.urls),
path('',include("main.urls")) path('',include("main.urls"))
] ]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

@ -1,4 +1,14 @@
"""
WSGI config for sahara project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/
"""
import os import os
from django.core.wsgi import get_wsgi_application from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sahara.settings') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sahara.settings')

Loading…
Cancel
Save