first commit

This commit is contained in:
Mohamad Jenbaz 2025-02-26 13:24:53 +01:00
commit 3b618dd791
21 changed files with 871 additions and 0 deletions

0
excel_mimic/__init__.py Normal file
View File

16
excel_mimic/asgi.py Normal file
View File

@ -0,0 +1,16 @@
"""
ASGI config for excel_mimic project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'excel_mimic.settings')
application = get_asgi_application()

124
excel_mimic/settings.py Normal file
View File

@ -0,0 +1,124 @@
"""
Django settings for excel_mimic project.
Generated by 'django-admin startproject' using Django 5.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-qsqw7#kmvlyc1ou5emdh8^_bqnvp+hui(4w#1yy4ui82+p=%p*'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sheets.apps.SheetsConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'excel_mimic.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
WSGI_APPLICATION = 'excel_mimic.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/5.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

23
excel_mimic/urls.py Normal file
View File

@ -0,0 +1,23 @@
"""
URL configuration for excel_mimic 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.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls), # Admin site
path('', include('sheets.urls')), # Sheets app URLs
]

16
excel_mimic/wsgi.py Normal file
View File

@ -0,0 +1,16 @@
"""
WSGI config for excel_mimic 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.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'excel_mimic.settings')
application = get_wsgi_application()

22
manage.py Normal file
View File

@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'excel_mimic.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

0
sheets/__init__.py Normal file
View File

2
sheets/admin.py Normal file
View File

@ -0,0 +1,2 @@
from django.contrib import admin

6
sheets/apps.py Normal file
View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class SheetsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'sheets'

7
sheets/forms.py Normal file
View File

@ -0,0 +1,7 @@
from django import forms
from .models import ExcelEntry
class ExcelEntryForm(forms.ModelForm):
class Meta:
model = ExcelEntry
fields = ['name', 'age', 'email'] # Include only the fields you want users to input

View File

@ -0,0 +1,21 @@
# Generated by Django 5.1.3 on 2024-12-04 13:22
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Sheet',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
],
),
]

View File

@ -0,0 +1,46 @@
# Generated by Django 5.1.3 on 2024-12-04 14:19
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sheets', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='MainColumn',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('sheet', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='main_columns', to='sheets.sheet')),
],
),
migrations.CreateModel(
name='Row',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('sheet', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rows', to='sheets.sheet')),
],
),
migrations.CreateModel(
name='SubColumn',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('main_column', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sub_columns', to='sheets.maincolumn')),
],
),
migrations.CreateModel(
name='Cell',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('value', models.CharField(blank=True, max_length=255, null=True)),
('row', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cells', to='sheets.row')),
('sub_column', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cells', to='sheets.subcolumn')),
],
),
]

View File

@ -0,0 +1,50 @@
# Generated by Django 5.1.4 on 2024-12-10 07:27
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sheets', '0002_maincolumn_row_subcolumn_cell'),
]
operations = [
migrations.RemoveField(
model_name='maincolumn',
name='sheet',
),
migrations.RemoveField(
model_name='subcolumn',
name='main_column',
),
migrations.RemoveField(
model_name='row',
name='sheet',
),
migrations.RenameModel(
old_name='Sheet',
new_name='Parent',
),
migrations.CreateModel(
name='Child',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('description', models.CharField(max_length=200)),
('parent', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='children', to='sheets.parent')),
],
),
migrations.DeleteModel(
name='Cell',
),
migrations.DeleteModel(
name='MainColumn',
),
migrations.DeleteModel(
name='SubColumn',
),
migrations.DeleteModel(
name='Row',
),
]

View File

@ -0,0 +1,29 @@
# Generated by Django 5.1.5 on 2025-01-22 13:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sheets', '0003_remove_maincolumn_sheet_remove_subcolumn_main_column_and_more'),
]
operations = [
migrations.CreateModel(
name='ExcelEntry',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('age', models.IntegerField()),
('email', models.EmailField(max_length=254)),
('date_joined', models.DateField(auto_now_add=True)),
],
),
migrations.DeleteModel(
name='Child',
),
migrations.DeleteModel(
name='Parent',
),
]

View File

@ -0,0 +1,23 @@
# Generated by Django 5.1.5 on 2025-02-17 10:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sheets', '0004_excelentry_delete_child_delete_parent'),
]
operations = [
migrations.CreateModel(
name='SecondTableEntry',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('age', models.IntegerField()),
('email', models.EmailField(max_length=254)),
('date_joined', models.DateField(auto_now_add=True)),
],
),
]

View File

19
sheets/models.py Normal file
View File

@ -0,0 +1,19 @@
from django.db import models
class ExcelEntry(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
email = models.EmailField()
date_joined = models.DateField(auto_now_add=True)
def __str__(self):
return self.name
class SecondTableEntry(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
email = models.EmailField()
date_joined = models.DateField(auto_now_add=True)
def __str__(self):
return self.name

View File

@ -0,0 +1,344 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Excel-like Table</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f4f4f9;
}
.container {
display: flex;
justify-content: space-between;
gap: 20px;
}
.table-container {
width: 48%;
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
color: #333;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #007bff;
color: white;
font-weight: bold;
}
tr:hover {
background-color: #f1f1f1;
}
.actions button {
margin: 2px;
padding: 5px 10px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
}
.edit-btn {
background-color: #28a745;
color: white;
}
.delete-btn {
background-color: #dc3545;
color: white;
}
.popup {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
z-index: 1000;
}
.popup input {
display: block;
margin-bottom: 10px;
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
}
.popup button {
margin-top: 10px;
padding: 8px 16px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
}
.close-btn {
cursor: pointer;
float: right;
font-size: 18px;
color: #333;
}
.add-row-btn {
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
margin-bottom: 20px;
}
.add-row-btn:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<h2>Excel-like Table</h2>
<div class="container">
<!-- First Table -->
<div class="table-container">
<button class="add-row-btn" id="add-row-1">Add Row</button>
<table id="table-1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Date Joined</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for entry in entries_table1 %}
<tr data-id="{{ entry.id }}">
<td>{{ entry.id }}</td>
<td>{{ entry.name }}</td>
<td>{{ entry.age }}</td>
<td>{{ entry.email }}</td>
<td>{{ entry.date_joined }}</td>
<td class="actions">
<button class="edit-btn">Edit</button>
<button class="delete-btn">Delete</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- Second Table -->
<div class="table-container">
<button class="add-row-btn" id="add-row-2">Add Row</button>
<table id="table-2">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Date Joined</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for entry in entries_table2 %}
<tr data-id="{{ entry.id }}">
<td>{{ entry.id }}</td>
<td>{{ entry.name }}</td>
<td>{{ entry.age }}</td>
<td>{{ entry.email }}</td>
<td>{{ entry.date_joined }}</td>
<td class="actions">
<button class="edit-btn">Edit</button>
<button class="delete-btn">Delete</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<!-- Add Entry Popup -->
<div id="add-popup" class="popup">
<span class="close-btn">&times;</span>
<h3>Add Entry</h3>
<input type="text" id="add-name" placeholder="Name">
<input type="number" id="add-age" placeholder="Age">
<input type="email" id="add-email" placeholder="Email">
<button id="save-add">Add</button>
</div>
<!-- Edit Entry Popup -->
<div id="edit-popup" class="popup">
<span class="close-btn">&times;</span>
<h3>Edit Entry</h3>
<input type="hidden" id="edit-id">
<input type="text" id="edit-name" placeholder="Name">
<input type="number" id="edit-age" placeholder="Age">
<input type="email" id="edit-email" placeholder="Email">
<button id="save-edit">Save</button>
</div>
<script>
$(document).ready(function () {
let currentTableId = null; // To track which table is being edited
let currentModelName = null; // To track which model is being used
// Open Add Popup for Table 1
$('#add-row-1').on('click', function () {
currentTableId = 'table-1';
currentModelName = 'ExcelEntry'; // Model name for Table 1
$('#add-popup').fadeIn();
});
// Open Add Popup for Table 2
$('#add-row-2').on('click', function () {
currentTableId = 'table-2';
currentModelName = 'SecondTableEntry'; // Model name for Table 2
$('#add-popup').fadeIn();
});
// Close Popups
$('.close-btn').on('click', function () {
$('.popup').fadeOut();
});
// Save Add Entry
$('#save-add').on('click', function () {
let name = $('#add-name').val();
let age = $('#add-age').val();
let email = $('#add-email').val();
$.ajax({
url: `/add-entry/${currentModelName}/`,
method: 'POST',
data: {
'name': name,
'age': age,
'email': email,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function (response) {
let newRow = `
<tr data-id="${response.id}">
<td>${response.id}</td>
<td>${response.name}</td>
<td>${response.age}</td>
<td>${response.email}</td>
<td>${response.date_joined}</td>
<td class="actions">
<button class="edit-btn">Edit</button>
<button class="delete-btn">Delete</button>
</td>
</tr>
`;
$(`#${currentTableId} tbody`).append(newRow);
$('#add-popup').fadeOut();
}
});
});
// Open Edit Popup
$(document).on('click', '.edit-btn', function () {
let row = $(this).closest('tr');
currentTableId = row.closest('table').attr('id'); // Set current table ID
currentModelName = currentTableId === 'table-1' ? 'ExcelEntry' : 'SecondTableEntry'; // Set model name
$('#edit-id').val(row.data('id'));
$('#edit-name').val(row.find('td:eq(1)').text());
$('#edit-age').val(row.find('td:eq(2)').text());
$('#edit-email').val(row.find('td:eq(3)').text());
$('#edit-popup').fadeIn();
});
// Save Edit Entry
$('#save-edit').on('click', function () {
let id = $('#edit-id').val();
let name = $('#edit-name').val();
let age = $('#edit-age').val();
let email = $('#edit-email').val();
$.ajax({
url: `/update-entry/${currentModelName}/`,
method: 'POST',
data: {
'id': id,
'name': name,
'age': age,
'email': email,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function (response) {
if (response.status === 'success') {
let row = $(`tr[data-id="${id}"]`);
row.find('td:eq(1)').text(name);
row.find('td:eq(2)').text(age);
row.find('td:eq(3)').text(email);
$('#edit-popup').fadeOut();
} else {
alert('Failed to update entry: ' + response.message);
}
},
error: function () {
alert('Failed to update entry. Please try again.');
}
});
});
// Delete Entry
$(document).on('click', '.delete-btn', function () {
let row = $(this).closest('tr');
let id = row.data('id');
currentTableId = row.closest('table').attr('id'); // Set current table ID
currentModelName = currentTableId === 'table-1' ? 'ExcelEntry' : 'SecondTableEntry'; // Set model name
if (!confirm('Are you sure you want to delete this entry?')) return;
$.ajax({
url: `/delete-entry/${currentModelName}/`,
method: 'POST',
data: {
'id': id,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function (response) {
if (response.status === 'success') {
row.fadeOut(300, function () { $(this).remove(); });
} else {
alert('Failed to delete entry: ' + response.message);
}
},
error: function () {
alert('Failed to delete entry. Please try again.');
}
});
});
});
</script>
</body>
</html>

3
sheets/tests.py Normal file
View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

9
sheets/urls.py Normal file
View File

@ -0,0 +1,9 @@
from django.urls import path
from . import views
urlpatterns = [
path('', views.excel_table_view, name='excel_table'),
path('add-entry/<str:model_name>/', views.add_entry, name='add_entry'),
path('update-entry/<str:model_name>/', views.update_entry, name='update_entry'),
path('delete-entry/<str:model_name>/', views.delete_entry, name='delete_entry'),
]

111
sheets/views.py Normal file
View File

@ -0,0 +1,111 @@
from django.shortcuts import render
from django.http import JsonResponse
from django.apps import apps
from datetime import date
# View to render the table page
def excel_table_view(request):
# Fetch existing entries from both tables
entries_table1 = apps.get_model('sheets', 'ExcelEntry').objects.all()
entries_table2 = apps.get_model('sheets', 'SecondTableEntry').objects.all()
return render(request, 'excel_table.html', {
'entries_table1': entries_table1,
'entries_table2': entries_table2,
})
# Generic view to add a new row to any table
def add_entry(request, model_name):
if request.method == 'POST':
try:
# Dynamically get the model
model = apps.get_model('sheets', model_name)
# Get data from the request
name = request.POST.get('name', 'New Name')
age = int(request.POST.get('age', 0))
email = request.POST.get('email', 'example@email.com')
# Create a new entry
entry = model.objects.create(
name=name,
age=age,
email=email,
date_joined=date.today()
)
# Return the new entry as JSON response
return JsonResponse({
'id': entry.id,
'name': entry.name,
'age': entry.age,
'email': entry.email,
'date_joined': entry.date_joined.strftime('%Y-%m-%d'),
})
except Exception as e:
return JsonResponse({'status': 'error', 'message': str(e)}, status=400)
return JsonResponse({'status': 'error', 'message': 'Invalid request'}, status=400)
# Generic view to update an entry in any table
def update_entry(request, model_name):
if request.method == 'POST':
try:
# Dynamically get the model
model = apps.get_model('sheets', model_name)
# Get data from the request
entry_id = int(request.POST.get('id'))
name = request.POST.get('name')
age = int(request.POST.get('age'))
email = request.POST.get('email')
# Fetch the entry to be updated
entry = model.objects.get(id=entry_id)
# Update the entry with new data
entry.name = name
entry.age = age
entry.email = email
entry.save()
# Return the updated entry as a JSON response
return JsonResponse({
'status': 'success',
'id': entry.id,
'name': entry.name,
'age': entry.age,
'email': entry.email,
'date_joined': entry.date_joined.strftime('%Y-%m-%d'),
})
except model.DoesNotExist:
return JsonResponse({'status': 'error', 'message': 'Entry not found'}, status=404)
except Exception as e:
return JsonResponse({'status': 'error', 'message': str(e)}, status=400)
return JsonResponse({'status': 'error', 'message': 'Invalid request'}, status=400)
# Generic view to delete an entry from any table
def delete_entry(request, model_name):
if request.method == 'POST':
try:
# Dynamically get the model
model = apps.get_model('sheets', model_name)
# Get the entry ID from the request
entry_id = request.POST.get('id')
# Find the entry by its ID and delete it
entry = model.objects.get(id=entry_id)
entry.delete()
# Return success response
return JsonResponse({'status': 'success', 'message': 'Entry deleted'})
except model.DoesNotExist:
return JsonResponse({'status': 'error', 'message': 'Entry not found'}, status=404)
except Exception as e:
return JsonResponse({'status': 'error', 'message': str(e)}, status=400)
return JsonResponse({'status': 'error', 'message': 'Invalid request'}, status=400)