file_name
stringlengths 7
47
| file_path
stringlengths 24
82
| code_content
stringlengths 0
11.1k
|
|---|---|---|
manage.py
|
django_project/manage.py
|
#!/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', 'django_project.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()
|
models.py
|
django_project/testbeds/models.py
|
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Testbed(models.Model):
device = models.TextField()
location = models.TextField()
telnet = models.TextField()
ssh = models.TextField()
notes = models.TextField(default="Add Notes")
device_type = models.TextField(default="ftd")
usage = models.TextField(default="notfree")
date_posted = models.DateTimeField(auto_now=True)
testbed_uploader = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.device
def get_absolute_url(self):
return reverse('testbed-detail', kwargs={'pk': self.pk})
|
cron.py
|
django_project/testbeds/cron.py
|
import time
from .models import Testbed
import requests
import datetime
from django.utils import timezone
from .constants import users, send_webex_message
druva='Y2lzY29zcGFyazovL3VzL1BFT1BMRS9jOWU2YjkzMi02OTMwLTQyMTktOWMzMi02MDg0NGZkYjVjZTY'
rdongare='Y2lzY29zcGFyazovL3VzL1BFT1BMRS9iZDViMjAyOC1kNjk4LTQwYjUtYTdmMC1jNzQzNDg3YzkxNjU'
# users = {'druva': 'Y2lzY29zcGFyazovL3VzL1BFT1BMRS9jOWU2YjkzMi02OTMwLTQyMTktOWMzMi02MDg0NGZkYjVjZTY',
# 'rdongare': 'Y2lzY29zcGFyazovL3VzL1BFT1BMRS9iZDViMjAyOC1kNjk4LTQwYjUtYTdmMC1jNzQzNDg3YzkxNjU'}
def my_cron_job():
headers={'Authorization': 'Bearer OGNkNjAyZmMtMjMwOC00N2IwLWJmMWEtZTVlNThiOWJjYjM1Y2I1NjkxMjctZWNh_PF84_1eb65fdf-9643-417f-9974-ad72cae0e10f', 'Content-type': 'application/json;charset=utf-8'}
devices = Testbed.objects.filter(usage='notfree',device_type='ftd') | Testbed.objects.filter(usage='notfree',device_type='fmc')
in_use_one_week = []
current_time = datetime.datetime.now(timezone.utc)
for device in devices:
delta_time = current_time - device.date_posted
# print(device, delta_time.seconds, delta_time.seconds > 3600)
if delta_time.days >= 4:
send_webex_message(True,device.testbed_uploader.username,device.device,sending_user=None)
|
constants.py
|
django_project/testbeds/constants.py
|
import requests
users = {'dpappire': ('Druva','Y2lzY29zcGFyazovL3VzL1BFT1BMRS9jOWU2YjkzMi02OTMwLTQyMTktOWMzMi02MDg0NGZkYjVjZTY'),
'rdongare': ('Rohit','Y2lzY29zcGFyazovL3VzL1BFT1BMRS9iZDViMjAyOC1kNjk4LTQwYjUtYTdmMC1jNzQzNDg3YzkxNjU'),
'shponnap': ('Shreya','Y2lzY29zcGFyazovL3VzL1BFT1BMRS9lZTE0YTVhMC1mMzlkLTRlNGEtYTBlMi04MWUyZTEzZGY3ZmE'),
'rajpill': ('Raj','Y2lzY29zcGFyazovL3VzL1BFT1BMRS84YzlkMDAxNi01NGRkLTQwZTktYTU3MS04MWI0OTVjYzVkNzE'),
'alapham': ('Alan','Y2lzY29zcGFyazovL3VzL1BFT1BMRS8wNGI5MGRmZC01MGJjLTRlYmEtOWU5ZC1lNDNmNzlkMWJlYzY'),
'anujjai2': ('Anuj','Y2lzY29zcGFyazovL3VzL1BFT1BMRS85MGJjODYyNC0wMjNkLTRjZmMtODZlNi1mZGUxYzhjMDUzM2U'),
'weilia': ('Wei','Y2lzY29zcGFyazovL3VzL1BFT1BMRS9kODI2Njk5Ny05ZmViLTRmOTAtODFjYy0yMDJmMTBkYzE4Yzk'),
'rskumar': ('Ramya','Y2lzY29zcGFyazovL3VzL1BFT1BMRS9lNjk5MWQ4NS01ZGE5LTRiN2ItOGU0NS0xNDBiYzVmYTg4Zjg'),
'sundaraj': ('Jaganathan','Y2lzY29zcGFyazovL3VzL1BFT1BMRS84MWQ1ZDBkMy03MGIzLTQyMmUtYjA2ZS0zMmVmOWY3MjljNDI')
}
headers={'Authorization': 'Bearer OGNkNjAyZmMtMjMwOC00N2IwLWJmMWEtZTVlNThiOWJjYjM1Y2I1NjkxMjctZWNh_PF84_1eb65fdf-9643-417f-9974-ad72cae0e10f', 'Content-type': 'application/json;charset=utf-8'}
def send_webex_message(weekly_message, username, device, sending_user=None):
body={'toPersonId': users[username][1]}
message = f'Device **{device}** has been In Use for over a week please reserve it again or release it'
if weekly_message:
body['markdown'] = message
else:
body['markdown'] = f'Hi {users[username][0]},\n' + message + f'\n-{users[sending_user][0]} ({sending_user}@cisco.com)'
requests.post('https://webexapis.com/v1/messages', json=body, headers=headers)
|
__init__.py
|
django_project/testbeds/__init__.py
| |
apps.py
|
django_project/testbeds/apps.py
|
from django.apps import AppConfig
class TestbedsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'testbeds'
|
forms.py
|
django_project/testbeds/forms.py
|
from django import forms
from .models import Testbed
# class MyPostTestbed(forms.ModelForm):
# # template_name = 'testbeds/testbed_form.html/'
# class Meta:
# model = Testbed
# fields = ['device','location', 'telnet', 'ssh']
# OPTIONS = [
# ('sjc15', 'sjc15'),
# ('sjc16', 'sjc16'),
# ('ful', 'ful'),
# ]
# selected_option = forms.ChoiceField(choices=OPTIONS, widget=forms.Select(attrs={'class': 'form-control'}))
class MyPostTestbed(forms.Form):
class Meta:
model = Testbed
fields = ['device', 'telnet', 'ssh' , 'location']
device = forms.CharField(label="device", max_length=100, required=True)
telnet = forms.CharField(label="telnet_connection", max_length=100, required=True)
ssh = forms.CharField(label="ssh_connection", max_length=100, required=True)
OPTIONS = [
('sjc15', 'sjc15'),
('sjc16', 'sjc16'),
('ful', 'ful'),
]
location = forms.ChoiceField(choices=OPTIONS, widget=forms.Select(attrs={'class': 'form-control'}))
class MyUpdateTestbed(forms.Form):
device = forms.CharField(label="device", widget=forms.Textarea(attrs={'class': 'fieldWrapper'}), max_length=100,)
telnet = forms.CharField(label="telnet", widget=forms.Textarea(attrs={'class': 'fieldWrapper'}), max_length=100,)
ssh = forms.CharField(label="ssh", widget=forms.Textarea(attrs={'class': 'fieldWrapper'}), max_length=100)
notes = forms.CharField(label="notes", widget=forms.Textarea(attrs={'class': 'fieldWrapper'}))
device_type = forms.CharField(label="device_type", widget=forms.Textarea(attrs={'class': 'fieldWrapper'}), max_length=100)
OPTIONS = [
('sjc15', 'sjc15'),
('sjc16', 'sjc16'),
('ful', 'ful'),
]
location = forms.ChoiceField(choices=OPTIONS, widget=forms.Select(attrs={'class': 'form-control'}))
OPTIONS = [
('notfree', 'In Use'),
('free', 'Not In Use')
]
usage = forms.ChoiceField(choices=OPTIONS, widget=forms.Select(attrs={'class': 'form-control'}))
OPTIONS = [
('ftd', 'FTD'),
('fmc', 'FMC'),
('router', 'Router'),
('switch', 'Switch')
]
device_type = forms.ChoiceField(choices=OPTIONS, widget=forms.Select(attrs={'class': 'form-control'}))
class Meta:
model = Testbed
fields = ('device', 'telnet', 'ssh' , 'location', 'notes', 'usage', 'device_type')
class ExcelForm(forms.Form):
generate_excel = forms.BooleanField(required=False, widget=forms.HiddenInput())
|
admin.py
|
django_project/testbeds/admin.py
|
from django.contrib import admin
# Register your models here.
|
tests.py
|
django_project/testbeds/tests.py
|
from django.test import TestCase
# Create your tests here.
|
filters.py
|
django_project/testbeds/filters.py
|
import django_filters
from django import forms
from .models import Testbed
class YourModelFilter(django_filters.FilterSet):
dropdown_option1 = django_filters.ChoiceFilter(
choices=[('all', 'all'), ('free', 'free'), ('used', 'notfree')],
label='Usage',
empty_label='all',
method='filter_dropdown_option1'
)
dropdown_option2 = django_filters.ChoiceFilter(
choices=[('latest', 'latest'), ('oldest', 'oldest')],
label='Date',
empty_label='oldest',
method='filter_dropdown_option2'
)
class Meta:
model = Testbed
fields = ['dropdown_option1','dropdown_option2']
def filter_dropdown_option1(self, queryset, name, value):
if value == "all":
return queryset
return queryset.filter(usage=value)
def filter_dropdown_option2(self, queryset, name, value):
if value == "latest":
return queryset.order_by('-date_posted')
return queryset.order_by('date_posted')
|
views.py
|
django_project/testbeds/views.py
|
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.utils.decorators import method_decorator
from django.shortcuts import render, redirect, get_object_or_404
from django_filters.views import FilterView
from django.contrib import messages
from django.views import View
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView
)
from .models import Testbed
from .forms import MyUpdateTestbed, ExcelForm
from .filters import YourModelFilter
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from openpyxl import Workbook
from django.http import HttpResponse
from .constants import users, send_webex_message
import datetime
from django.utils import timezone
button_submited ={'Submitted': False}
location_dict = {'sjc15': 'San Jose Building 15',
'sjc16': 'San Jose Building 16',
'ful': 'Fulton'}
device_type_dict = {'all': 'All',
'ftd': 'FTD',
'fmc': 'FMC',
'router': 'Router',
'switch': 'Switch'}
date_dict = {'latest': ('Latest', "Latest"),
'oldest': ('Oldest', "Oldest")}
usage_dict = {'all': ('All', "all", "All Devices"),
'not_used': ('Unused', "free", "Unused Devices"),
'used': ('Used', "notfree", "Used Devices")}
@method_decorator(login_required, name='dispatch')
class TestbedListView(ListView):
model = Testbed
template_name = 'testbed-home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'testbeds'
context = {'title': 'Devices Home'}
def get(self, request):
generate_excel = self.request.GET.get('generate_excel')
if generate_excel:
wb = Workbook()
ws = wb.active
headers = ['Username','Location','Device','Usage','Date','Type','Telnet','SSH','Notes']
ws.append(headers)
objs = Testbed.objects.all()
for data in objs:
username = str(data.testbed_uploader)
row_data = [str(data.testbed_uploader),data.location,data.device,data.usage,str(data.date_posted),data.device_type,data.telnet,data.ssh,data.notes]
ws.append(row_data)
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=my_excel_file.xlsx'
wb.save(response)
return response
return render(request, self.template_name, {'title': 'Devices Home'})
@method_decorator(login_required, name='dispatch')
class TestbedDetailListView(ListView):
model = Testbed
template_name = 'location-detail.html'
context_object_name = 'devices'
def get_context_data(self):
location = self.kwargs.get('parameter') # Get the category parameter from URL
selected_date = self.request.GET.get('date','oldest')
selected_usage = self.request.GET.get('usage','all')
selected_user = self.request.GET.get('user','all')
selected_device_type = self.request.GET.get('device_type','all')
searched_device = self.request.GET.get('search_device','')
submitted_button = self.request.GET.get('submitted_button')
order_by = "date_posted"
if submitted_button == "Submit":
submitted_button = "Reset-and-Submit"
else:
submitted_button = 'Submit'
searched_device = ""
temp_usage = usage_dict[selected_usage]
temp_date = date_dict[selected_date]
temp_device_type = device_type_dict[selected_device_type]
device_objects = Testbed.objects.filter(location=location)
if searched_device:
device_objects = device_objects.filter(device=searched_device)
all_users = User.objects.all()
if device_objects:
order_by_message_str = "Filter Date: Oldest"
if 'latest' in selected_date:
order_by = "-date_posted"
order_by_message_str = "Filter Date: Latest"
if selected_usage != "all":
device_objects = device_objects.filter(usage=temp_usage[1])
username = "All"
if selected_user != "all":
device_objects = device_objects.filter(testbed_uploader=selected_user)
username = User.objects.filter(id=selected_user)[0].username
# device_type = "All"
if selected_device_type != "all":
device_objects = device_objects.filter(device_type=selected_device_type)
device_type = device_type_dict[selected_device_type]
messages.success(self.request, f'Filter Date: {temp_date[1]}, Filter Usage: {temp_usage[2]}, Filter User: {username}, Filter User: {temp_device_type}')
paginator = Paginator(device_objects.order_by(order_by), per_page=5)
page_number = self.request.GET.get('page',1)
page_obj = paginator.get_page(page_number)
context = {'devices': paginator.page(int(page_number)), "is_paginated":True, 'page_obj': page_obj, "location": location_dict[location],
'date': selected_date, 'usage': selected_usage, 'all_users': all_users, 'selected_date': temp_date[0], 'selected_usage': temp_usage[0],
'selected_user': username, 'selected_device_type': temp_device_type, 'searched_device': searched_device, 'submit_button_name': submitted_button,
'title': f'Devices:- {location_dict[location]}'}
return context
else:
paginator = Paginator(device_objects.order_by(order_by), per_page=5)
page_number = self.request.GET.get('page',1)
page_obj = paginator.get_page(page_number)
messages.error(self.request, f'Device {searched_device} does not exist')
return {'devices': paginator.page(int(page_number)),'submit_button_name': submitted_button}
def post(self, request, *args, **kwargs):
pk = self.request.POST.get('pk_val')
location = self.kwargs.get('parameter')
obj = get_object_or_404(Testbed,pk=pk)
testbed_uploader = obj.testbed_uploader.username
device = obj.device
user = request.user.username
if request.method == 'POST':
send_webex_message(False,testbed_uploader,device,sending_user=user)
return redirect('location-detail', location)
@method_decorator(login_required, name='dispatch')
class PostTestbed(CreateView):
template_name = 'testbeds/testbed_form.html'
def get(self, request, *args, **kwargs):
form = MyUpdateTestbed()
return render(request, self.template_name)
def post(self, request, *args, **kwargs):
form = MyUpdateTestbed(request.POST)
if form.is_valid():
context = {'form': form}
device = request.POST.get('device', '')
telnet = request.POST.get('telnet', '')
ssh = request.POST.get('ssh', '')
location = request.POST.get('location', '')
notes = request.POST.get('notes')
usage = request.POST.get('usage','')
device_type = request.POST.get('device_type','')
user = request.user
existing_device = Testbed.objects.filter(device=device)
existing_telnet = Testbed.objects.filter(telnet=telnet)
existing_ssh = Testbed.objects.filter(ssh=ssh)
if existing_device.exists() and existing_device[0].location == location:
messages.error(request, f'Name already exists in {location}')
return render(request, self.template_name, {'context': context})
elif existing_telnet.exists():
messages.error(request, f'Telnet Connection Entered already exists in {location_dict[existing_telnet[0].location]} for device {existing_telnet[0].device}')
return render(request, self.template_name, {'context': context})
elif Testbed.objects.filter(ssh=ssh).exists():
messages.error(request, f'SSH Connection details already exists in {location_dict[existing_ssh[0].location]} for device {existing_ssh[0].device}')
return render(request, self.template_name, {'context': context})
else:
testbed = Testbed(device=device,
ssh=ssh,
telnet=telnet,
location=location,
notes=notes,
usage=usage,
device_type=device_type,
testbed_uploader=user)
testbed.save()
messages.success(request, f'Testbed {device} Details Uploaded Succesfully!') # Set success message
return render(request, "testbeds/testbed-home.html", {"context": context})
@method_decorator(login_required, name='dispatch')
class TestbedUpdateView(View):
model = Testbed
template_name = 'testbeds/testbed-detail.html'
def get(self, request, pk):
obj = get_object_or_404(Testbed, pk=pk)
form = MyUpdateTestbed(initial={'device': obj.device, 'location': obj.location, 'telnet': obj.telnet,
'ssh': obj.ssh, 'notes': obj.notes, 'usage': obj.usage, 'device_type': obj.device_type})
return render(request, self.template_name, {'form': form, 'object': obj})
def check_existing_object(self,existing_obj,current_pk):
if existing_obj:
if len(existing_obj) == 1:
existing_pk = existing_obj[0].pk
return (existing_pk != current_pk, existing_pk)
return (False, None)
def post(self, request, pk, *args, **kwargs):
obj = get_object_or_404(Testbed, pk=pk)
form = MyUpdateTestbed(request.POST)
if form.is_valid():
context = {'form': form}
device = form.cleaned_data['device']
location = form.cleaned_data['location']
telnet = form.cleaned_data['telnet']
ssh = form.cleaned_data['ssh']
notes = form.cleaned_data['notes']
usage = form.cleaned_data['usage']
device_type = form.cleaned_data['device_type']
obj.device = device
obj.location = location
obj.telnet = telnet
obj.ssh = ssh
obj.notes = notes
obj.usage = usage
obj.device_type = device_type
obj.testbed_uploader = request.user
# obj.date_posted = datetime.datetime.now(timezone.utc)
existing_telnet_obj = Testbed.objects.filter(telnet=telnet)
existing_ssh_obj = Testbed.objects.filter(ssh=ssh)
existing_device_obj = Testbed.objects.filter(location=location,device=device)
if existing_device_obj and existing_device_obj[0].pk != pk:
messages.error(request, f'This Name already exists in {location_dict[location]}. Please use a different name')
return render(request, "testbeds/testbed-detail.html", {'form': form, 'object': obj})
if existing_telnet_obj and existing_telnet_obj[0].pk != pk:
messages.error(request, f'Telnet Details already exists for {existing_telnet_obj[0].device} in {d[existing_telnet_obj[0].location]}')
return render(request, "testbeds/testbed-detail.html", {'form': form, 'object': obj})
if existing_ssh_obj and existing_ssh_obj[0].pk != pk:
messages.error(request, f'SSH Details already exists for {existing_ssh_obj[0].device} in {d[location]}')
return render(request, "testbeds/testbed-detail.html", {'form': form, 'object': obj})
obj.save()
messages.success(request, f'Update Succesful!') # Set success message
return redirect('location-detail', location)
@method_decorator(login_required, name='dispatch')
class TestbedDeleteView(View):
template_name = 'testbeds/testbed-delete.html'
def get(self, request, pk):
# Get the object you want to delete
obj = get_object_or_404(Testbed, pk=pk)
context = {
'object': obj,
}
return render(request, self.template_name, context)
def post(self, request, pk):
obj = get_object_or_404(Testbed, pk=pk)
location = obj.location
if not request.user.is_superuser:
messages.error(request, 'You do not have Permission to Delete Devices')
return redirect('location-detail', location)
obj.delete()
return redirect('location-detail', location)
|
0006_testbed_device_type.py
|
django_project/testbeds/migrations/0006_testbed_device_type.py
|
# Generated by Django 4.2.9 on 2024-01-26 18:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('testbeds', '0005_testbed_usage_alter_testbed_location'),
]
operations = [
migrations.AddField(
model_name='testbed',
name='device_type',
field=models.TextField(default='FTD'),
),
]
|
0007_alter_testbed_device_type.py
|
django_project/testbeds/migrations/0007_alter_testbed_device_type.py
|
# Generated by Django 4.2.9 on 2024-01-26 19:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('testbeds', '0006_testbed_device_type'),
]
operations = [
migrations.AlterField(
model_name='testbed',
name='device_type',
field=models.TextField(default='ftd'),
),
]
|
0002_rename_user_testbed_testbed_uploader.py
|
django_project/testbeds/migrations/0002_rename_user_testbed_testbed_uploader.py
|
# Generated by Django 4.2.9 on 2024-01-09 22:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('testbeds', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='testbed',
old_name='user',
new_name='testbed_uploader',
),
]
|
0005_testbed_usage_alter_testbed_location.py
|
django_project/testbeds/migrations/0005_testbed_usage_alter_testbed_location.py
|
# Generated by Django 4.2.9 on 2024-01-19 20:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('testbeds', '0004_alter_testbed_location'),
]
operations = [
migrations.AddField(
model_name='testbed',
name='usage',
field=models.TextField(default='notfree'),
),
migrations.AlterField(
model_name='testbed',
name='location',
field=models.TextField(),
),
]
|
0004_alter_testbed_location.py
|
django_project/testbeds/migrations/0004_alter_testbed_location.py
|
# Generated by Django 4.2.9 on 2024-01-19 20:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('testbeds', '0003_testbed_notes_alter_testbed_date_posted'),
]
operations = [
migrations.AlterField(
model_name='testbed',
name='location',
field=models.TextField(default='notfree'),
),
]
|
__init__.py
|
django_project/testbeds/migrations/__init__.py
| |
0003_testbed_notes_alter_testbed_date_posted.py
|
django_project/testbeds/migrations/0003_testbed_notes_alter_testbed_date_posted.py
|
# Generated by Django 4.2.9 on 2024-01-19 19:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('testbeds', '0002_rename_user_testbed_testbed_uploader'),
]
operations = [
migrations.AddField(
model_name='testbed',
name='notes',
field=models.TextField(default='Add Notes'),
),
migrations.AlterField(
model_name='testbed',
name='date_posted',
field=models.DateTimeField(auto_now=True),
),
]
|
0001_initial.py
|
django_project/testbeds/migrations/0001_initial.py
|
# Generated by Django 4.2.9 on 2024-01-08 23:59
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Testbed',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('device', models.TextField()),
('location', models.TextField()),
('telnet', models.TextField()),
('ssh', models.TextField()),
('date_posted', models.DateTimeField(default=django.utils.timezone.now)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
|
testbed-main.css
|
django_project/testbeds/static/testbeds/testbed-main.css
|
body {
background: #fafafa;
color: #333333;
margin-top: 5rem;
}
.hidden-data {
display: none;
}
.testbed-content {
background: #ffffff;
padding: 10px 20px;
border: 1px solid #dddddd;
border-radius: 3px;
margin-bottom: 20px;
}
header {
background-color: #3498db;
color: #fff;
padding: 10px;
text-align: center;
}
.container {
width: 80%;
margin: 20px auto;
background-color: #fff;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.data-list {
list-style: none;
padding: 0;
margin: 0;
}
.data-list li {
border-bottom: 1px solid #ccc;
padding: 10px;
display: flex;
justify-content: space-between;
align-items: center;
}
.data-list li:last-child {
border-bottom: none;
}
/* Add hover effect for better user experience */
.data-list li:hover {
background-color: #f9f9f9;
}
|
registration.css
|
django_project/testbeds/static/testbeds/registration.css
|
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.container {
max-width: 400px;
margin: 50px auto;
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
color: #333;
padding: 10px;
margin-bottom: 16px;
/* border: 1px solid #ddd;*/
border-radius: 4px;
}
form {
display: flex;
flex-direction: column;
}
.select_option {
padding: 10px;
margin-bottom: 16px;
border: 1px solid #ddd;
border-radius: 4px;
color: #555;
}
label {
margin-bottom: 8px;
color: #555;
}
input {
padding: 10px;
margin-bottom: 16px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
background-color: #4caf50;
color: #fff;
padding: 10px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
margin-top: 20px;
margin-bottom: 20px;
}
.btn-info {
background-color: white;
color: blue;
padding: 10px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
margin-bottom: 20px;
}
button:hover {
background-color: darkcyan;
}
.btn-info:hover {
background-color: darkred;
}
li {
color: red;
font-size: 20px;
}
table {
border-collapse: collapse;
width: 100%;
margin-bottom: 20px;
overflow-x: auto;
}
td {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
.fieldWrapper {
padding: 10px;
margin-top: -5px;
margin-bottom: 30px;
/* border: 1px solid #ddd;*/
border-radius: 4px;
height: 50px;
width: 100%;
}
|
location-detail.html
|
django_project/testbeds/templates/testbeds/location-detail.html
|
{% extends "blog/base.html" %}
{% block content %}
{% for field in form %}
{{ field.errors }}
{% endfor %}
<form method="get">
{{ form.as_p }}
<!-- <button type="submit", name='latest' class="btn btn-outline-secondary">Latest</button>
<button type="submit", name='oldest' class="btn btn-outline-secondary">Oldest</button> -->
<label for="date_dropdown"></label>
<select class="select select_option" id="date" name="date">
<option value="" disabled selected>Date:- {{ selected_date }}</option>
<option value="latest">Latest</option>
<option value="oldest">Oldest</option>
</select>
<label for="usage_dropdown"></label>
<select class="select select_option" id="usage" name="usage">
<option value="" disabled selected>Usage:- {{ selected_usage }}</option>
<option value="all">All</option>
<option value="not_used">Unused Devices</option>
<option value="used">Used Devices</option>
</select>
<label for="device_type_dropdown"></label>
<select class="select select_option" id="device_type" name="device_type">
<option value="" disabled selected>Type:- {{ selected_device_type }}</option>
<option value="all">All</option>
<option value="ftd">FTD</option>
<option value="fmc">FMC</option>
<option value="router">Router</option>
<option value="switch">Switch</option>
</select>
<label for="user_dropdown"></label>
<select class="select select_option" id="user" name="user">
<option value="" disabled selected>User:- {{ selected_user }}</option>
<option value="all">All</option>
{% for user in all_users %}
<option value="{{ user.id }}">{{ user.username }}</option>
{% endfor %}
</select>
<label for="search_device"></label>
<input class="select select_option" type="text" id="search_device" name="search_device" placeholder="Type your search..." value={{ searched_device}}>
<!-- <button class="btn btn-primary btn-sm mt-1 mb-1" id="submit_button" name="submit_button" type="submit">{{ submit_button_name }}</button> -->
<input type="submit" name = "submitted_button" class="btn btn-primary btn-sm mt-1 mb-1" value={{ submit_button_name }}>
</form>
{% for testbed in devices %}
<div class="media-body">
<button onclick="toggleData('data{{ forloop.counter }}')" class="testbed-content" style="background-color: {% if testbed.usage == 'free' %}green{% else %}red{% endif %};">{{ testbed.device }} </button>
<div id="data{{ forloop.counter }}" class="hidden-data" style="overflow-x:auto;">
<table>
<form method="post">
{% csrf_token %}
<button class="btn btn-info btn-sm mt-1 mb-1" type="submit" name='pk_val' value={{ testbed.id }}>Remind User</button>
</form>
<tr>
<td>Type</td>
<td>{% if testbed.device_type == 'ftd' %}FTD{% elif testbed.device_type == 'fmc'%}FMC{% elif testbed.device_type == 'router'%}Router{% else %}Switch{% endif %}</td>
</tr>
<tr>
<td>Location</td>
<td>{{ location }}</td>
</tr>
<tr>
<td>Telnet</td>
<td>{{ testbed.telnet }}</td>
</tr>
<tr>
<td>SSH </td>
<td>{{ testbed.ssh }}</td>
</tr>
<tr>
<td>Notes</td>
<td>
{{ testbed.notes }}
</td>
</tr>
<tr>
<td>Usage</td>
<td>{% if testbed.usage == 'free' %}Not In Use{% else %}In Use{% endif %}</td>
</tr>
<tr>
<td>User</td>
<td>{{ testbed.testbed_uploader }}</td>
</tr>
<tr>
<td>Added/Edited</td>
<td>{{ testbed.date_posted }}</td>
</tr>
</table>
<!-- Add more content as needed -->
<a class="btn btn-primary btn-sm mt-1 mb-1" href="{% url 'testbed-detail' testbed.id %}">Update</a>
{% if user.is_superuser %}
<a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'testbed-delete' testbed.id %}">Delete</a>
{% endif %}
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'location-detail' testbed.location %}">Close</a>
</div>
</div>
{% endfor %}
{% if is_paginated %}
{% if page_obj.has_previous %}
<a class="btn btn-outline-info mb-4" href="?page=1&date={{ date }}&usage={{ usage }}">First</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}&date={{ date }}&usage={{ usage }}">Previous</a>
{% endif %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
<a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a>
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
<a class="btn btn-outline-info mb-4" href="?page={{ num }}&date={{ date }}&usage={{ usage }}">{{ num }}</a>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}&date={{ date }}&usage={{ usage }}">Next</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}&date={{ date }}&usage={{ usage }}">Last</a>
{% endif %}
{% endif %}
<script>
function toggleData(id) {
var hiddenData = document.getElementById(id);
hiddenData.style.display = !hiddenData.style.display ? 'block' : '';
}
</script>
{% endblock content %}
|
testbed-detail.html
|
django_project/testbeds/templates/testbeds/testbed-detail.html
|
{% load static %}
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="{% static 'testbeds/registration.css' %}">
<title>Update Testbed</title>
</head>
<body>
<div class="container">
<h2>Update Testbed</h2>
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<form method="post">
{% csrf_token %}
<label>Location:</label>
<div class="fieldWrapper">
{{ form.location }}
</div>
<label>Device Type:</label>
<div class="fieldWrapper">
{{ form.device_type }}
</div>
<label>Device Name:</label>
<div class="fieldWrapper">
{{ form.device }}
</div>
<label>Telnet:</label>
<div class="fieldWrapper">
{{ form.telnet }}
</div>
<label>SSH:</label>
<div class="fieldWrapper">
{{ form.ssh }}
</div>
<label>Notes:</label>
<div class="fieldWrapper">
{{ form.notes }}
</div>
<label>Usage:</label>
<div class="fieldWrapper">
{{ form.usage }}
</div>
<button type="submit">Update</button>
<a href="{% url 'testbed-home' %}" class="btn btn-info">Cancel</a>
</form>
</div>
</body>
</html>
|
testbed-delete.html
|
django_project/testbeds/templates/testbeds/testbed-delete.html
|
{% extends "blog/base.html" %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Delete Tested</legend>
<h2>Are you sure you want to delete Device {{ object.device }} from location {{ object.location }}</h2>
</fieldset>
<div class="form-group">
<button class="btn btn-outline-danger" type="submit">Yes, Delete</button>
<a class="btn btn-outline-secondary" href="{% url 'location-detail' object.location %}">Cancel</a>
</div>
</form>
</div>
{% endblock content %}
|
testbed-home.html
|
django_project/testbeds/templates/testbeds/testbed-home.html
|
{% extends "blog/base.html" %}
{% block content %}
<header>
<h1>List of Locations</h1>
</header>
<div>
{% if error_message %}
<div class="error-message">
<h5 class="error-message-display">{{ error_message }}</h5>
<a class="close-button" onclick="closeErrorMessage()">X</a>
</div>
<script>
function closeErrorMessage() {
document.querySelector('.error-message').style.display = 'none';
}
</script>
{% endif %}
<section>
<h2><a href="{% url 'location-detail' 'sjc15'%}" class="location-title">San Jose Building 15</a></h2>
</section>
<section>
<h2><a href="{% url 'location-detail' 'sjc16'%}" class="location-title">San Jose Building 16</a></h2>
</section>
<section>
<h2><a href="{% url 'location-detail' 'ful'%}" class="location-title">Fulton</a></h2>
</section>
</div>
<a href="{% url 'testbed_form' %}" class="btn add-testbed">Add Testbed</a>
<div>
<div>
{% if user.is_superuser %}
<form method="get">
<button type="submit" name = "generate_excel" class="btn add-testbed" value="generate_excel">Generate Excel</button>
<!-- <input type="submit" name = "generate_excel" class="btn add-testbed" value="Generate Excel"> -->
</form>
{% endif %}
</div>
</div>
{% endblock content %}
<!-- <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> -->
<!-- <h2><a class="article-title" href="{% url 'location-detail' %}">{{ testbed }}</a></h2> -->
<!-- <h2><a class="article-title" href="{% url 'location-testbed-detail' %}">{{ testbed }}</a></h2> -->
|
testbed_form.html
|
django_project/testbeds/templates/testbeds/testbed_form.html
|
{% load static %}
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="{% static 'testbeds/registration.css' %}">
<title>Add Device</title>
</head>
<body>
<div class="container">
<h2>Add New Device</h2>
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<form method="post">
{% csrf_token %}
<label for="name">Username:</label>
<input type="text" id="name" name="name" value={{ user.username }} readonly>
<label for="dropdown">Location:</label>
<select id="dropdown" class="select select_option" name="location" required>
<option value="" disabled selected>Select an Option</option>
<option value="sjc15">sjc15</option>
<option value="sjc16">sjc16</option>
<option value="ful">ful</option>
<!-- Add more options as needed -->
</select>
<label for="dropdown">Device Type:</label>
<select id="dropdown" class="select select_option" name="device_type" required>
<option value="" disabled selected>Select an Option</option>
<option value="ftd">FTD</option>
<option value="fmc">FMC</option>
<option value="router">Router</option>
<option value="switch">Switch</option>
<!-- Add more options as needed -->
</select>
<label for="device">Device name:</label>
<input type="device" id="device" name="device" required>
<label for="ssh">SSH Connection:</label>
<input type="ssh" id="ssh" name="ssh" required>
<label for="telnet">TELNET Connection:</label>
<input type="telnet" id="telnet" name="telnet" required>
<label for="notes">Notes:</label>
<input type="notes" id="notes" name="notes" value="Add Notes">
<label for="dropdown">Status:</label>
<select id="dropdown" class="select select_option" name="usage" required>
<option value="notfree">In Use</option>
<option value="free">Not In Use</option>
</select>
<button type="submit">Add Testbed</button>
<a href="{% url 'testbed-home' %}" class="btn btn-info">Cancel</a>
</form>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
|
models.py
|
django_project/chatbot/models.py
|
from django.db import models
# Create your models here.
|
__init__.py
|
django_project/chatbot/__init__.py
| |
apps.py
|
django_project/chatbot/apps.py
|
from django.apps import AppConfig
class ChatbotConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'chatbot'
|
admin.py
|
django_project/chatbot/admin.py
|
from django.contrib import admin
# Register your models here.
|
tests.py
|
django_project/chatbot/tests.py
|
from django.test import TestCase
# Create your tests here.
|
views.py
|
django_project/chatbot/views.py
|
from django.shortcuts import render
from django.http import HttpResponse
import openai
# from openai import OpenAI
# Create your views here.
client = openai.OpenAI(api_key='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')
openai_api_key = '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'
def ask_openai(message):
response = client.chat.completions.create(
model = "gpt-3.5-turbo",
messages = [{"role": "user", "content": message}],
# max_tokens=150,
# n=1,
# stop=None,
# temperature=0.7,
)
return response.choices[0].message.content
def chatbot(request):
return render(request, 'chatbot.html', {'title': 'Chatbot'})
def getResponse(request):
userMessage = request.GET.get('userMessage')
response_openai = ask_openai(userMessage)
return HttpResponse(response_openai)
|
__init__.py
|
django_project/chatbot/migrations/__init__.py
| |
chatbot.css
|
django_project/chatbot/static/chatbot/chatbot.css
|
#chatbot{
margin-left: auto;
margin-right: auto;
width: 50%;
margin-top: 50px;
border-radius: 10px;
border: 1px solid green;
padding: 10px;
color: black;
background-color: cyan;
}
#userbot{
margin-left: auto;
margin-right: 0;
width: 50%;
margin-top: 50px;
border-radius: 10px;
border: 1px solid green;
padding: 10px;
background-color: lightseagreen;
}
.botText{
/* font-family: monospace;*/
font-size: 14px;
text-align: left;
line-height: 25px;
color: grey;
}
#userInput{
margin-left: auto;
margin-right: auto;
margin-top: 40px;
width: 70%;
text-align: center;
}
#textInput{
border: 3px solid white;
border-bottom: 3px solid grey;
font-family: monospace;
font-size: 14px;
width: 60%;
padding: 16px;
color: red;
}
#buttonInput{
padding: 5px;
/* font-family: monospace;*/
font-size: 14px;
border: 3px sold;
background-color: green;
color: white;
border-radius: 10px;
cursor: pointer;
}
#buttonInput:hover {
background-color: lightskyblue;
color: black;
}
#buttonInput:focus {
background: lightskyblue;
color: black;
}
h1{
text-align: center;
color: teal;
margin-top: 10px;
}
.userText{
text-align: right;
font-family: monospace;
font-size: 14px;
line-height: 25px;
color: grey;
}
|
chatbot.html
|
django_project/chatbot/templates/chatbot.html
|
{% load static %}
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="{% static 'chatbot/chatbot.css' %}">
<script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
<title>ChatBot</title>
</head>
<body>
<h1>Chatbot</h1>
<div>
<div id="chatbot">
<p class="botText"><span>Hi There,</span></p>
</div>
<!-- <div id="userbot">
<p class="botText"><span></span></p>
</div> -->
<div id="userInput">
<input type="text" id="textInput" name="userMessage" placeholder="Type your message....."/>
<input type="submit" value="Send" id="buttonInput"/>
</div>
</div>
<script type="text/javascript">
function getUserResponse(){
var userText = $('#textInput').val();
if (userText) {
var userHTML = "<p class='userText'>User: <span>"+userText+"</span></p>"
$('#textInput').val("");
$('#chatbot').append(userHTML)
$.get('/getResponse',{ userMessage:userText}).done(function(data){
var returnedMessage = "<p class='botText'>Chatbot: <span>"+ data +"</span></p>";
$('#chatbot').append(returnedMessage);
})
}
}
$('#buttonInput').click(function(){
getUserResponse();
})
</script>
</body>
</html>
|
asgi.py
|
django_project/django_project/asgi.py
|
"""
ASGI config for django_project 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/4.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_project.settings')
application = get_asgi_application()
|
__init__.py
|
django_project/django_project/__init__.py
| |
settings.py
|
django_project/django_project/settings.py
|
"""
Django settings for django_project project.
Generated by 'django-admin startproject' using Django 4.2.9.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
from pathlib import Path
import os
import ssl
import certifi
ssl._create_default_https_context = ssl._create_unverified_context
# 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/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-b%jxn9pmiu#!-+eo$+&w376rst)(&^lepr^m*og+j7v_s1xz#-'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'blog.apps.BlogConfig',
'users.apps.UsersConfig',
'testbeds.apps.TestbedsConfig',
'chatbot.apps.ChatbotConfig',
'django_crontab',
'django_filters',
'crispy_forms',
'crispy_bootstrap4',
'widget_tweaks',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
#CRONJOBS = [
# ('0 18 * * *', 'testbeds.cron.my_cron_job')
#]
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 = 'django_project.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 = 'django_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/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/4.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Los_Angeles'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = 'static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
LOGIN_REDIRECT_URL = 'blog-home'
LOGIN_URL = 'login'
Allow_Reset = False
|
urls.py
|
django_project/django_project/urls.py
|
"""
URL configuration for django_project project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.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, re_path
from django.views.generic import TemplateView
from django.contrib.auth import views as auth_views
from django.urls import path, include
from users import views as user_views
from testbeds import views as testbeds_views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', user_views.register, name='register'),
path('profile/', user_views.profile, name='profile'),
path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
path('password-reset/', user_views.ResetPasswordView.as_view(template_name='users/password_reset.html'), name='password_reset'),
path('password-reset/password-reset-confirm/', user_views.ResetPasswordConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'),
path('', include('blog.urls')),
re_path(r'^.*/$', TemplateView.as_view(template_name='blog/404.html'), name='custom_404'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
wsgi.py
|
django_project/django_project/wsgi.py
|
"""
WSGI config for django_project 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/4.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_project.settings')
application = get_wsgi_application()
|
models.py
|
django_project/blog/models.py
|
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
|
__init__.py
|
django_project/blog/__init__.py
| |
apps.py
|
django_project/blog/apps.py
|
from django.apps import AppConfig
class BlogConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'blog'
|
admin.py
|
django_project/blog/admin.py
|
from django.contrib import admin
from .models import Post
admin.site.register(Post)
|
tests.py
|
django_project/blog/tests.py
|
from django.test import TestCase
# Create your tests here.
|
urls.py
|
django_project/blog/urls.py
|
from django.urls import path
from .views import (
PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
UserPostListView
)
from testbeds import views as testbeds_views
from chatbot import views as chatbot_views
from . import views
from users import views as users_views
urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('testbed-home/',testbeds_views.TestbedListView.as_view(template_name='testbeds/testbed-home.html'),name="testbed-home"),
path('location-detail/<str:parameter>/',testbeds_views.TestbedDetailListView.as_view(template_name='testbeds/location-detail.html'),name="location-detail"),
path('location-detail/<int:pk>/update/',testbeds_views.TestbedUpdateView.as_view(template_name='testbeds/testbed-detail.html'),name="testbed-detail"),
path('location-detail/<int:pk>/delete/',testbeds_views.TestbedDeleteView.as_view(template_name='testbeds/testbed-delete.html'),name="testbed-delete"),
path('testbed_form/',testbeds_views.PostTestbed.as_view(template_name='testbeds/testbed_form.html'),name="testbed_form"),
path('about/', views.about, name='blog-about'),
path('chatbot/', chatbot_views.chatbot, name='chatbot'),
path('getResponse/', chatbot_views.getResponse, name='getResponse'),
# path('custom_404/', views.custom_404, name='blog-404'),
]
# <app>/<model>_<viewtype>.html
|
views.py
|
django_project/blog/views.py
|
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User
from django.utils.decorators import method_decorator
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView
)
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import Post
from django.db.models import Q
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
@login_required
def home(request):
context = {
'posts': Post.objects.all()
}
return render(request, 'blog/home.html', context)
@login_required
def about(request):
return render(request, 'blog/about.html', {'title': 'About Blog'})
def test(request):
return render(request, 'blog/add_testbed.html', {'title': 'Test Blog'})
def custom_404(request):
return render(request, 'blog/404.html', {'title': 'Page Not Found'})
@method_decorator(login_required, name='dispatch')
class PostListView(ListView):
model = Post
template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
ordering = ['-date_posted']
# paginate_by = 3
# def get_queryset(self):
# # obj = get_object_or_404(Post)
# # print(self.request.GET.get('submitted_button'))
# blogs = []
# if self.request.GET.get('submitted_button'):
# searched_blog = self.request.GET.get('search_blog','')
# return Post.objects.filter(Q(title__icontains=searched_blog) | Q(content__icontains=searched_blog)).order_by('-date_posted')
# return Post.objects.all().order_by('-date_posted')
def get_context_data(self):
searched_blog = self.request.GET.get('search_blog','')
post_obj = Post.objects.all().order_by('-date_posted')
if searched_blog:
post_obj = Post.objects.filter(Q(title__icontains=searched_blog) | Q(content__icontains=searched_blog)).order_by('-date_posted')
paginator = Paginator(post_obj, per_page=3)
page_number = self.request.GET.get('page',1)
page_obj = paginator.get_page(page_number)
context = {'posts': paginator.page(int(page_number)),"is_paginated":True, 'page_obj': page_obj,'searched_blog': searched_blog}
return context
class UserPostListView(ListView):
model = Post
template_name = 'blog/user_posts.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
paginate_by = 3
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get('username'))
return Post.objects.filter(author=user).order_by('-date_posted')
@method_decorator(login_required, name='dispatch')
class PostDetailView(DetailView):
model = Post
@method_decorator(login_required, name='dispatch')
class PostCreateView(CreateView):
model = Post
fields = ['title', 'content']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin, UpdateView):
model = Post
fields = ['title', 'content']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Post
success_url = '/'
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
|
0002_testbedpost.py
|
django_project/blog/migrations/0002_testbedpost.py
|
# Generated by Django 4.2.9 on 2024-01-08 23:59
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('blog', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='TestbedPost',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('username', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
|
__init__.py
|
django_project/blog/migrations/__init__.py
| |
0003_delete_testbedpost.py
|
django_project/blog/migrations/0003_delete_testbedpost.py
|
# Generated by Django 4.2.9 on 2024-01-19 19:52
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_testbedpost'),
]
operations = [
migrations.DeleteModel(
name='TestbedPost',
),
]
|
0001_initial.py
|
django_project/blog/migrations/0001_initial.py
|
# Generated by Django 4.2.9 on 2024-01-06 01:31
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('content', models.TextField()),
('date_posted', models.DateTimeField(default=django.utils.timezone.now)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
|
404.css
|
django_project/blog/static/blog/404.css
|
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.container {
max-width: 400px;
margin: 50px auto;
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
color: #333;
}
p {
text-align: center;
color: #555;
}
|
main.css
|
django_project/blog/static/blog/main.css
|
body {
background: #fafafa;
color: #333333;
margin-top: 5rem;
}
h1, h2, h3, h4, h5, h6 {
color: #444444;
}
label.reset{
padding: 10px;
float: left;
margin-right: 15px;
}
input.reset {
padding: 10px;
margin-bottom: 16px;
margin-left: 15px;
margin-right: 15px;
border: 1px solid #ddd;
border-radius: 14px;
float: center;
}
.select_option {
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ddd;
border-radius: 5px;
color: #555;
}
.search_blog {
padding: 10px;
margin-bottom: 25px;
border: 1px solid #ddd;
border-radius: 5px;
color: #555;
width: 90%;
}
.error-message {
display: flex;
margin-bottom: 10px;
}
.error-message-display{
font-weight: bold;
color: red;
font-size: 30px;
border: 1px;
padding: 5px;
margin-bottom: 10px;
}
.close-button {
margin-top: -15px;
color: black;
cursor: pointer;
color: blue;
border-radius: 4px;
padding: 5px;
}
ul {
margin: 0;
}
.bg-steel {
background-color: #5f788a;
}
.site-header .navbar-nav .nav-link {
color: #cbd5db;
}
.site-header .navbar-nav .nav-link:hover {
color: #ffffff;
}
.site-header .navbar-nav .nav-link.active {
font-weight: 500;
}
.content-section {
background: #ffffff;
padding: 10px 20px;
border: 1px solid #dddddd;
border-radius: 3px;
margin-bottom: 20px;
}
.article-title {
color: #444444;
}
/* Following section is for Testbed Homepage */
/*Testbed Homepage START*/
.location-title {
color: dodgerblue;
font-size: 25px;
}
.add-testbed .location-title {
color: dodgerblue;
font-size: 25px;
}
.add-testbed {
background-color: green;
color: white;
padding: 10px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 20px;
margin-bottom: 20px;
margin-left: 150px;
}
/*Testbed Homepage END*/
a.article-title:hover {
color: #428bca;
text-decoration: none;
}
.article-content {
white-space: pre-line;
overflow: scroll;
height: 250px;
width: 600px;
}
.article-content-detail {
overflow: scroll;
white-space: pre-line;
width: 600px;
}
.article-img {
height: 65px;
width: 65px;
margin-right: 16px;
}
.article-metadata {
padding-bottom: 1px;
margin-bottom: 4px;
border-bottom: 1px solid #e3e3e3
}
.article-metadata a:hover {
color: #333;
text-decoration: none;
}
.article-svg {
width: 25px;
height: 25px;
vertical-align: middle;
}
.account-img {
height: 125px;
width: 125px;
margin-right: 20px;
margin-bottom: 16px;
}
.account-heading {
font-size: 2.5rem;
}
.limited-height-textfield {
max-height: 100px; /* Set the maximum height as per your requirement */
overflow-y: auto; /* Add scrollbar if the content overflows */
}
.testbed-content {
margin-top: 20px;
background: ghostwhite;
padding: 10px 20px;
border: 1px solid;
border-radius: 3px;
margin-bottom: 20px;
}
.increased-font {
font-size: 25px;
}
table {
border-collapse: collapse;
width: 100%;
height:100%;
max-height: 100px;
margin-bottom: 20px;
overflow-x: auto;
overflow-y: scroll;
}
td {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
height:100%;
max-height: 100px; /* Set a maximum height for the cell */
overflow-y: scroll;
}
.hidden-data {
display: none;
border: 1px solid;
padding: 5px;
background: whitesmoke;
height:100%;
margin-bottom: 40px;
overflow-x: auto;
}
.article-title-testbed {
color: green;
margin-bottom: 20px;
}
colorButton {
background-color: blue;
color: white;
}
#colorButton.selected {
background-color: green;
}
alert-link{color:#062c33}.alert-error{
font-size: 20px;
color:black;
background-color:red;
border-color:#ffeeba;
}.alert-error
hr{
border-top-color:#ffe8a1
}.alert-error
|
post_confirm_delete.html
|
django_project/blog/templates/blog/post_confirm_delete.html
|
{% extends "blog/base.html" %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Delete Post</legend>
<h2>Are you sure you want to delete the post "{{ object.title }}"</h2>
</fieldset>
<div class="form-group">
<button class="btn btn-outline-danger" type="submit">Yes, Delete</button>
<a class="btn btn-outline-secondary" href="{% url 'post-detail' object.id %}">Cancel</a>
</div>
</form>
</div>
{% endblock content %}
|
home.html
|
django_project/blog/templates/blog/home.html
|
{% extends "blog/base.html" %}
{% block content %}
<form method='get'>
<label for="search_device"></label>
<input class="select search_blog" type="text" id="search_blog" name="search_blog" placeholder="Type your search...">
<input type="submit" name = "submitted_button" class="btn btn-primary btn-sm mt-1 mb-1" value="Search">
<span id="clearSearch" style="cursor: pointer; display: none;">✖</span>
</form>
<!-- <script>
$(document).ready(function() {
var searchInput = $('#search_blog');
var clearSearch = $('#clearSearch');
// Show or hide the clear button based on the input value
searchInput.on('input', function() {
clearSearch.toggle(!!this.value);
});
// Clear the input field when the clear button is clicked
clearSearch.click(function() {
searchInput.val('').focus();
clearSearch.hide();
});
});
</script> -->
{% for post in posts%}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted|date:"d F Y f A T" }}</small>
</div>
<h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
<p class="article-content">{{ post.content }}</p>
</div>
</article>
{% endfor %}
{% if is_paginated %}
{% if page_obj.has_previous %}
<a class="btn btn-outline-info mb-4" href="?page=1&search_blog={{ searched_blog }}">First</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}&search_blog={{ searched_blog }}">Previous</a>
{% endif %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
<a class="btn btn-info mb-4" href="?page={{ num }}&search_blog={{ searched_blog }}">{{ num }}</a>
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
<a class="btn btn-outline-info mb-4" href="?page={{ num }}&search_blog={{ searched_blog }}">{{ num }}</a>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}&search_blog={{ searched_blog }}">Next</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}&search_blog={{ searched_blog }}">Last</a>
{% endif %}
{% endif %}
{% endblock content %}
|
about.html
|
django_project/blog/templates/blog/about.html
|
{% extends "blog/base.html" %}
{% block content %}
<h1>About Page</h1>
{% endblock content %}
|
base.html
|
django_project/blog/templates/blog/base.html
|
{% load static %}
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}">
{% if title %}
<title>{{ title }}</title>
{% else %}
<title>Blog Home</title>
{% endif %}
</head>
<body>
<header class="site-header">
<nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
<div class="container">
<a class="navbar-brand mr-4" href="{% url 'blog-home' %}">Blog</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarToggle">
<div class="navbar-nav mr-auto">
<a class="nav-item nav-link" href="{% url 'blog-home' %}">Home</a>
<a class="nav-item nav-link" href="{% url 'blog-about' %}">About</a>
<a class="nav-item nav-link" href="{% url 'testbed-home' %}">Devices</a>
</div>
<!-- Navbar Right Side -->
<div class="navbar-nav">
{% if user.is_authenticated %}
<a class="nav-item nav-link" href="{% url 'profile' %}">Profile</a>
<a class="nav-item nav-link" href="{% url 'post-create' %}">New Post</a>
<a class="nav-item nav-link" href="{% url 'logout' %}">Logout</a>
{% else %}
<a class="nav-item nav-link" href="{% url 'login' %}">Login</a>
<a class="nav-item nav-link" href="{% url 'register' %}">Register</a>
{% endif %}
</div>
</div>
</div>
</nav>
</header>
<main role="main" class="container">
<div class="row">
<div class="col-md-8">
{% if messages %}
{% for message in messages %}
{% if message.tags == 'error' %}
<div class="alert alert-error">
{{ message }}
</div>
{% else %}
<div class="alert alert-{{message.tags}}">
{{ message }}
</div>
{% endif %}
{% endfor %}
{% endif %}
{% block content %}{% endblock %}
</div>
<div class="col-md-4">
<div class="content-section">
<h3>Our Sidebar</h3>
<p class='text-muted'>You can put any information here you'd like.
<ul class="list-group">
<li class="list-group-item list-group-item-light">Latest Posts</li>
<li class="list-group-item list-group-item-light">Announcements</li>
<li class="list-group-item list-group-item-light">Calendars</li>
<li class="list-group-item list-group-item-light">etc</li>
</ul>
</p>
<div>
{% if user.is_authenticated %}
<a href="{% url 'chatbot' %}" class="btn btn-info">Ask Me</a>
{% endif %}
</div>
</div>
</div>
</div>
</main>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
|
post_form.html
|
django_project/blog/templates/blog/post_form.html
|
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Blog Post</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Post</button>
</div>
</form>
</div>
{% endblock content %}
|
404.html
|
django_project/blog/templates/blog/404.html
|
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page Not Found</title>
<link rel="stylesheet" href="{% static 'css/404.css' %}">
</head>
<body>
<div class="container">
<h1>404 - Page Not Found</h1>
<p>Sorry, the page you requested does not exist.</p>
</div>
</body>
</html>
|
add_sidebar.html
|
django_project/blog/templates/blog/add_sidebar.html
| |
post_detail.html
|
django_project/blog/templates/blog/post_detail.html
|
{% extends "blog/base.html" %}
{% block content %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="#">{{ object.author }}</a>
<small class="text-muted">{{ object.date_posted|date:"d F Y f A T" }}</small>
</div>
<div>
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a>
<a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a>
</div>
<h2 class="article-title">{{ object.title }}</h2>
<p class="article-content-detail">{{ object.content }}</p>
</div>
</article>
{% endblock content %}
|
user_posts.html
|
django_project/blog/templates/blog/user_posts.html
|
{% extends "blog/base.html" %}
{% block content %}
<h1 class="mb-3">Posts by {{ view.kwargs.username }} ({{ page_obj.paginator.count }})</h1>
{% for post in posts %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
</div>
<h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
<p class="article-content">{{ post.content }}</p>
</div>
</article>
{% endfor %}
{% if is_paginated %}
{% if page_obj.has_previous %}
<a class="btn btn-outline-info mb-4" href="?page=1">First</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a>
{% endif %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
<a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a>
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
<a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a>
{% endif %}
{% endif %}
{% endblock content %}
|
signals.py
|
django_project/users/signals.py
|
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
|
models.py
|
django_project/users/models.py
|
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
email = models.EmailField()
bio = models.TextField(blank=True, null=True)
linkedin = models.TextField(blank=True, null=True)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
def save(self,** kwargs):
super().save()
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)
|
constants.py
|
django_project/users/constants.py
|
import requests
import random
users = {'dpappire': ('Druva','Y2lzY29zcGFyazovL3VzL1BFT1BMRS9jOWU2YjkzMi02OTMwLTQyMTktOWMzMi02MDg0NGZkYjVjZTY'),
'rdongare': ('Rohit','Y2lzY29zcGFyazovL3VzL1BFT1BMRS9iZDViMjAyOC1kNjk4LTQwYjUtYTdmMC1jNzQzNDg3YzkxNjU'),
'shponnap': ('Shreya','Y2lzY29zcGFyazovL3VzL1BFT1BMRS9lZTE0YTVhMC1mMzlkLTRlNGEtYTBlMi04MWUyZTEzZGY3ZmE'),
'rajpill': ('Raj','Y2lzY29zcGFyazovL3VzL1BFT1BMRS84YzlkMDAxNi01NGRkLTQwZTktYTU3MS04MWI0OTVjYzVkNzE'),
'alapham': ('Alan','Y2lzY29zcGFyazovL3VzL1BFT1BMRS8wNGI5MGRmZC01MGJjLTRlYmEtOWU5ZC1lNDNmNzlkMWJlYzY'),
'anujjai2': ('Anuj','Y2lzY29zcGFyazovL3VzL1BFT1BMRS85MGJjODYyNC0wMjNkLTRjZmMtODZlNi1mZGUxYzhjMDUzM2U'),
'weilia': ('Wei','Y2lzY29zcGFyazovL3VzL1BFT1BMRS9kODI2Njk5Ny05ZmViLTRmOTAtODFjYy0yMDJmMTBkYzE4Yzk'),
'rskumar': ('Ramya','Y2lzY29zcGFyazovL3VzL1BFT1BMRS9lNjk5MWQ4NS01ZGE5LTRiN2ItOGU0NS0xNDBiYzVmYTg4Zjg'),
'sundaraj': ('Jaganathan','Y2lzY29zcGFyazovL3VzL1BFT1BMRS84MWQ1ZDBkMy03MGIzLTQyMmUtYjA2ZS0zMmVmOWY3MjljNDI')
}
# shponnap Y2lzY29zcGFyazovL3VzL1BFT1BMRS9lZTE0YTVhMC1mMzlkLTRlNGEtYTBlMi04MWUyZTEzZGY3ZmE
# rajpill Y2lzY29zcGFyazovL3VzL1BFT1BMRS84YzlkMDAxNi01NGRkLTQwZTktYTU3MS04MWI0OTVjYzVkNzE
# dpappire Y2lzY29zcGFyazovL3VzL1BFT1BMRS9jOWU2YjkzMi02OTMwLTQyMTktOWMzMi02MDg0NGZkYjVjZTY
# alapham Y2lzY29zcGFyazovL3VzL1BFT1BMRS8wNGI5MGRmZC01MGJjLTRlYmEtOWU5ZC1lNDNmNzlkMWJlYzY
# anujjai2 Y2lzY29zcGFyazovL3VzL1BFT1BMRS85MGJjODYyNC0wMjNkLTRjZmMtODZlNi1mZGUxYzhjMDUzM2U
# weilia Y2lzY29zcGFyazovL3VzL1BFT1BMRS9kODI2Njk5Ny05ZmViLTRmOTAtODFjYy0yMDJmMTBkYzE4Yzk
# rskumar Y2lzY29zcGFyazovL3VzL1BFT1BMRS9lNjk5MWQ4NS01ZGE5LTRiN2ItOGU0NS0xNDBiYzVmYTg4Zjg
headers={'Authorization': 'Bearer OGNkNjAyZmMtMjMwOC00N2IwLWJmMWEtZTVlNThiOWJjYjM1Y2I1NjkxMjctZWNh_PF84_1eb65fdf-9643-417f-9974-ad72cae0e10f', 'Content-type': 'application/json;charset=utf-8'}
def send_webex_message(username):
body={'toPersonId': users[username][1]}
random_code = ''.join(random.choices('0123456789', k=5))
message = f'Enter the code {random_code}'
body['markdown'] = message
requests.post('https://webexapis.com/v1/messages', json=body, headers=headers)
return random_code
|
__init__.py
|
django_project/users/__init__.py
| |
apps.py
|
django_project/users/apps.py
|
from django.apps import AppConfig
class UsersConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'users'
def ready(self):
import users.signals
|
forms.py
|
django_project/users/forms.py
|
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image', 'bio', 'linkedin']
widgets = {
'linkedin': forms.Textarea(attrs={'cols': 40, 'rows': 1}),
}
|
admin.py
|
django_project/users/admin.py
|
from django.contrib import admin
from .models import Profile
admin.site.register(Profile)
|
tests.py
|
django_project/users/tests.py
|
from django.test import TestCase
# Create your tests here.
|
views.py
|
django_project/users/views.py
|
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.views.generic import UpdateView
from django.views import View
from django.contrib.auth.models import User
from django.utils.decorators import method_decorator
from .constants import send_webex_message
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
from .models import Profile
import time
allowed_users = ['shponnap','rajpill', 'dpappire', 'alapham', 'anujjai2','weilia','rskumar'],
user_dict = {'rdongare': (0,'test_password'), 'shponnap': (0, 'test'), 'rajpill': (0, 'test'), 'dpappire': (0, 'test'), 'alapham': (0, 'test'), 'anujjai2': (0, 'test'), 'weilia': (0, 'test'), 'rskumar': (0, 'test')}
time_dict = {'start_time': time.time()}
def register(request):
if request.method == "POST":
form = UserRegisterForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
if username in allowed_users:
form.save()
messages.success(request, f'Account Created!')
return redirect('login')
else:
messages.error(request,f'{username} is not a valid Username! Please use your cec username')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
@login_required
def profile(request):
if request.method == 'POST':
is_post_request = True
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST,
request.FILES,
instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
username = u_form.cleaned_data.get('username')
if username in allowed_users:
u_form.save()
p_form.save()
messages.success(request, f'Your account has been updated!')
return redirect('profile')
else:
messages.error(request, f'{username} is not a valid Username! Please use your cec username')
return redirect('profile')
else:
is_post_request = False
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {'u_form': u_form,
'p_form': p_form}
return render(request, 'users/profile.html', context)
class ResetPasswordView(UpdateView):
model = Profile
template = 'password_reset.html'
def get(self,request):
return render(request, self.template_name)
def post(self, request, *args, **kwargs):
username = self.request.POST.get('username')
password = self.request.POST.get('password')
code = send_webex_message(username)
user_dict[username] = (code,password)
time_dict['start_time'] = time.time()
return render(request, 'users/password_reset_done.html')
class ResetPasswordConfirmView(UpdateView):
model = Profile
# template = 'password_reset_confirm.html'
def get(self,request):
return render(request, self.template_name)
def post(self, request, *args, **kwargs):
username = self.request.POST.get('username')
code = self.request.POST.get('code')
if username and time.time()-time_dict['start_time'] < 60:
if code == user_dict[username][0]:
u = User.objects.get(username=username)
u.set_password(user_dict[username][1])
u.save()
user_dict[username] = (0,'test')
return render(request, 'users/password_reset_complete.html')
messages.error(self.request, f'Codes provided do not match')
messages.error(self.request, f'You did not enter code within 1 minute')
return render(request, 'users/password_reset_incomplete.html')
|
0002_profile_linkedin.py
|
django_project/users/migrations/0002_profile_linkedin.py
|
# Generated by Django 4.2.9 on 2024-01-08 05:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='profile',
name='linkedin',
field=models.TextField(blank=True, null=True),
),
]
|
__init__.py
|
django_project/users/migrations/__init__.py
| |
0001_initial.py
|
django_project/users/migrations/0001_initial.py
|
# Generated by Django 4.2.9 on 2024-01-08 04:30
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Profile',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('email', models.EmailField(max_length=254)),
('bio', models.TextField(blank=True, null=True)),
('image', models.ImageField(default='default.jpg', upload_to='profile_pics')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
|
profile.html
|
django_project/users/templates/users/profile.html
|
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% load widget_tweaks %}
{% block content %}
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ user.username }}</h2>
<p class="text-secondary">{{ user.email }}</p>
</div>
</div>
<section class="bio">
<h2>Bio</h2>
<p>{{ user.profile.bio }} </p>
</section>
<section class="social-links mb-4">
<h2>LinkedIn Link</h2>
<ul>
<!-- <li><a href="https://twitter.com/johndoe" target="_blank">Linkedin</a></li> -->
{% if user.profile.linkedin %}
<li><a href="{{ user.profile.linkedin }}" target="_blank">LinkedIn</a></li>
{% else %}
<p>No link available.</p>
{% endif %}
</ul>
</section>
<section class="update-section">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4 ">Profile Info</legend>
{{ u_form|crispy }}
{{ p_form|crispy }}
<!-- {{ p_form.linkedin|add_class:"limited-height-textfield" }} -->
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Update</button>
</div>
</form>
</section>
</div>
{% endblock content %}
|
password_reset_done.html
|
django_project/users/templates/users/password_reset_done.html
|
{% extends "blog/base.html" %}
{% block content %}
<div class="alert alert-info">
A Code has been set to your Webex Enter it within 1 minute
</div>
<div>
<small class="text-muted">
Enter Code <a class="ml-2" href="{% url 'password_reset_confirm' %}">Reset Password?</a>
</small>
</div>
{% endblock content %}
|
register.html
|
django_project/users/templates/users/register.html
|
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Join Today</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a>
</small>
</div>
</div>
{% endblock content %}
|
password_reset.html
|
django_project/users/templates/users/password_reset.html
|
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="post">
{% csrf_token %}
<div>
<label class="reset" for="username">Your Username:</label>
<input class="reset" type="username" id="username" name="username" required>
</div>
<div>
<label class="reset" for="password">New Password: </label>
<input class="reset" type="password" id="password" name="password" required>
</div>
<button class="btn btn-outline-info" type="submit">Request Code to Password Reset</button>
</form>
</div>
{% endblock content %}
|
login.html
|
django_project/users/templates/users/login.html
|
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Log In</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Login</button>
</div>
<small class="text-muted ml-2">
<a href="{% url 'password_reset' %}">Forgot Password?</a>
</small>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Need An Account? <a class="ml-2" href="{% url 'register' %}">Sign Up Now</a>
</small>
</div>
</div>
{% endblock content %}
|
password_reset_incomplete.html
|
django_project/users/templates/users/password_reset_incomplete.html
|
{% extends "blog/base.html" %}
{% block content %}
<a href="{% url 'login' %}">Back to login Page</a>
{% endblock content %}
|
password_reset_confirm.html
|
django_project/users/templates/users/password_reset_confirm.html
|
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="post">
{% csrf_token %}
<div class="form-group">
<label class="reset" for="username">Username:</label>
<input class="reset" type="username" id="username" name="username" required>
</div>
<div>
<label class="reset" for="code">Enter Code:</label>
<input class="reset" type="code" id="code" name="code" required>
</div>
<button class="btn btn-outline-info" type="submit">Reset Password</button>
</form>
</div>
{% endblock content %}
|
password_reset_complete.html
|
django_project/users/templates/users/password_reset_complete.html
|
{% extends "blog/base.html" %}
{% block content %}
<div class="alert alert-info">
Your password has been set.
</div>
<a href="{% url 'login' %}">Sign In Here</a>
{% endblock content %}
|
logout.html
|
django_project/users/templates/users/logout.html
|
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<h2>You have been logged out</h2>
<div class="border-top pt-3">
<small class="text-muted">
<a href="{% url 'login' %}" class="increased-font">Log In Again</a>
</small>
</div>
{% endblock content %}
|
README.md exists but content is empty.
- Downloads last month
- 2