**models.py**
from django.db import models
from django.db.models.fields import CharField
from django.contrib import admin
# Create your models here.
class Contact(models.Model):
name = models.CharField(max_length=50, primary_key=True)
contact = models.CharField(max_length=50, default='')
address = models.TextField(max_length=50, default='')
program = models.CharField(max_length=50, default='')
email = models.CharField(max_length=50, default="")
w3review = models.TextField(max_length=60, default="")
def __str__(self):
return self.name
class Cv(models.Model):
filename = models.CharField(max_length=20)
upload = models.FileField(upload_to='cv')
def __str__(self):
return self.filename
**views.py**
from django.http import request, response
from django.http.response import HttpResponse
from django.shortcuts import render, redirect
import weasyprint
from .models import Contact
from django.http import HttpResponse, Http404
from django.conf import settings
import datetime
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login, logout
from django.template.loader import render_to_string
from weasyprint import HTML
import tempfile
from django.db.models import Sum
from .forms import CreateUserForm
import csv
import os
from django.contrib import messages
from django.contrib.auth.decorators import login_required
import csv, io
from .forms import ResultForm
# Create your views here.
def index(request):
if request.method == 'POST':
name = request.POST.get('name', '')
contact = request.POST.get('contact', '')
address = request.POST.get('address', '')
# program2 = request.POST.get('program2', '')
# bba = request.POST.get('bba', '')
# bhm = request.POST.get('bhm', '')
email = request.POST.get('email', '')
program = request.POST.get('program', '')
w3review = request.POST.get('w3review', '')
# if request.POST.get('program'):
# savevalue = Contact()
# savevalue.program=request.POST.get('program')
# savevalue.save()
if name and contact and address and email and program and w3review:
contact = Contact(name=name, contact=contact, address=address, email=email, program=program, w3review=w3review)
contact.save()
else:
return HttpResponse("Enter all details")
return render(request, 'index.html')
@login_required(login_url='login')
def export(request):
response = HttpResponse(content_type='text/csv')
writer = csv.writer(response)
writer.writerow(['name', 'contact', 'address', 'email', 'program', 'w3review'])
for contacts in Contact.objects.all().values_list('name', 'contact', 'address', 'email', 'program', 'w3review'):
writer.writerow(contacts)
response['Content-Disposition'] = 'attachment; filename="contactss.csv"'
return response
# def download(request, filepath):
# file_path = os.path.join(settings.MEDIA_ROOT, filepath)
# if os.path.exists(file_path):
# with open(file_path, 'rb') as fh:
# response = HttpResponse(fh.read(), content_type='application/pdf')
# response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
# return response
# return render(request, 'download.html', {'filepath': filepath})
@login_required(login_url='login')
def export_pdf(request):
response = HttpResponse(content_type='application/pdf')
response["Content-Disposition"] = 'inline; attachment; filename=Contact' + \
str(datetime.datetime.now())+'.pdf'
response["Content-Transfer-Encoding"] = 'binary'
expenses = Contact.objects.all()
# sum = expenses.aggregate(Sum('amount'))
html_string = render_to_string(
'expenses/pdf-output.html', {'expenses': expenses})
html = HTML(string=html_string)
result = html.write_pdf()
with tempfile.NamedTemporaryFile(delete=True) as output:
output.write(result)
output.flush()
output=open(output.name, 'rb')
response.write(output.read())
return response
def registerPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
user = form.cleaned_data.get('username')
messages.success(request, 'Account was created for ' + user)
return redirect('login')
context = {'form': form}
return render(request, 'expenses/register.html', context)
def loginPage(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.info(request, 'Username or Password is Incorrect')
context = {}
return render(request, 'expenses/login.html', context)
login_required
def logoutUser(request):
logout(request)
return redirect('index')
@login_required(login_url='login')
def homePage(request):
return render(request, 'home.html')
# upload csv file
############################Upload CSV File ##############################################################
def profile_upload(request):
template = "profile_upload.html"
data = Contact.objects.all()
# prompt is a context variable that can have different values depending on their context
prompt = {
'order': 'Order of the CSV should be name, address, contact, program, email, w3review',
'profiles': data
}
# Get request returns the value of the data with the specified key.
if request.method == 'GET':
return render(request, template, prompt)
csv_file = request.FILES['file']
# let's check if it is csv file or not
if not csv_file.name.endswith('.csv'):
messages.error(request, 'This is not a csv file')
data_set = csv_file.read().decode('UTF-8')
# setup a stream which is when we loop through each line we are able to handle a data in a stream.
io_string = io.StringIO(data_set)
next(io_string)
for column in csv.reader(io_string, delimiter=',', quotechar="|"):
_, created = Contact.objects.update_or_create(
name = column[0],
address = column[1],
contact = column[2],
program = column[3],
email = column[4],
w3review = column[5]
)
context = {}
return render(request, template, context)
# Exam result search applicaiton
def result_need(request):
form = ResultForm(request.POST or None)
template_name= 'result.html'
context = {"form": form}
if form.is_valid():
objects = Contact.objects.filter(name=form.cleaned_data['Name'])
context['objects'] = objects
return render(request, template_name, context)
forms.py
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
from django.db import models
from django.forms import fields
from django.forms.forms import Form
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = [‘username’, ‘email’, ‘password1’, ‘password2’]
class ResultForm(forms.Form):
Name = forms.CharField(label=‘Your Name’)