How to open an uploaded file in another template - Django? - django

my django app acts as an emailing service, emails that are sent are view-able and it's possible to send html emails. How do I display the html emails on the view-mail page rather than just displaying the name of the file ? (the following is the mail-view for an html email):
How would I display the actual html in the body of this page?
This is my views.py:
def outbox(request):
#Mail_Item.objects.all().delete()
if request.method == "POST" and request.POST.get('Username', False)!=False:
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, backend='django.contrib.auth.backends.ModelBackend')
print(username + " has logged in")
messages = Mail_Item.objects.filter(user=request.user.username)
args = {'messages':messages}
return render(request, 'outbox.html', args)
else:
return render(request, '404.html')
elif request.POST.get('Username', False) == False and request.POST.get('mail_body_field', False) == False:
pass
elif request.method == "POST" and request.POST.get('mail_subject_field')!=False:
subject = request.POST.get('mail_subject_field')
body = request.POST['mail_body_field']
file = ""
try:
file = request.FILES['filename']
except:
pass
print("sending mail:")
for i in range(1, len(Res)+1):
y = Res['ID' + str(i)].email
print("sent to " + y )
msg = EmailMessage(subject, body, 'email#example.com', [y])
msg.content_subtype = "html"
if (str(file)) != "" and (str(file))[-4:] != 'html':
msg.attach_file(str(file))
obj = Mail_Item(subject=subject, body=body, user=request.user.username, file_name=(str(file)))
obj.save()
print("email stored in database")
elif (str(file)) != "" and (str(file))[-4:] == 'html' :
uploaded_file = file
fs = FileSystemStorage()
fs.save((str(file)), uploaded_file)
html_message = render_to_string((str(file)), {'context': 'values'})
plain_message = strip_tags(html_message)
from_email = 'From <email2#example.com>'
mail.send_mail(subject, plain_message, from_email, [y], html_message=html_message)
obj = Mail_Item(subject=subject, body=body, user=request.user.username, file_name=(str(file)))
obj.save()
else:
obj = Mail_Item(subject=subject, body=body, user=request.user.username, file_name='None')
obj.save()
print("email stored in database")
#msg.send()
i += 1
messages = Mail_Item.objects.filter(user=request.user.username)
args = {'messages':messages}
return HttpResponseRedirect('../templates/outbox.html', args, request)
else:
print("pleeeeeaassee")
return render(request, '404.html')
messages = Mail_Item.objects.filter(user=request.user.username)
args = {'messages':messages}
return render(request, 'outbox.html', args)
def login_page(request):
if request.method == "POST":
username = request.POST['sign-up-name']
email = request.POST['sign-up-email']
password = request.POST['sign-up-password']
user = User.objects.create_user(username, email, password)
user.save()
print(username + " has been added to the user database.")
else:
pass
return render(request, 'login.html')
def signup_page(request):
return render(request, 'signup.html')
def mail_view(request, id=None):
if id:
email = Mail_Item.objects.get(id=id)
args = {'email':email}
else:
pass
return render(request, 'mail-view.html', args)
def log_out(request):
logout(request)
return render(request, 'log-out.html')
def delete(request):
Mail_Item.objects.filter(id=id).delete()
messages = Mail_Item.objects.filter(user=request.user.username)
args = {'messages':messages}
return render(request, 'outbox.html', args)
This is the code for my mail-view template where I'd like to place the html that is being sent:
<div class="mail-view">
<h4 class="m-0">{{ email.subject }}</h4>
<div class="divid"></div>
<div class="media">
<div class="media-left">
<div class="avatar avatar-lg avatar-circle">
<img class="img-responsive" src="{% static '../static/assets/images/221.jpg' %}" alt="avatar"/>
</div><!-- .avatar -->
</div>
<div class="media-body">
<div class="m-b-sm">
<h4 class="m-0 inline-block m-r-lg">
Access Bank
</h4>
</div>
<p><b>Attachment: </b>{{ email.file_name }}</p>
</div>
</div>
<div class="divid"></div>
<div class="row">
<div class="col-md-12">
<div class="m-h-lg lh-xl">
<p>{{ email.body }}</p>
</div>
</div>
</div>
</div>
Models.py:
from django.db import models
class Details(models.Model):
email = models.CharField(max_length=200)
def __str__(self):
return self.email
class Mail_Item(models.Model):
subject = models.CharField(max_length=200)
body = models.CharField(max_length=300)
time = models.DateTimeField(auto_now=True)
user = models.CharField(max_length=15)
file_name = models.CharField(max_length=100, null=True, default=None)
def __str__(self):
template = '{0.subject} {0.body} {0.time} {0.user} {0.file_name}'
return template.format(self)

Related

Django session variable change in UI everytime when new request_id is created

I want to request id differ in every page data, same as request id is in available in approve_url .
index function send session variable approve_url in test function.
Here is index function
global j, k, approve_url
#api_view(['POST', 'GET'])
def index(request):
# j = ''
# approve_url = ''
if request.method == "POST":
form = InputForm(request.POST)
if form.is_valid():
form.save()
try:
ids = form.cleaned_data['git_Id']
print(ids)
obj = sql()
query = f""" SELECT request_id FROM request_form_db.request_form_mymodel
where git_Id= '{ids}' ;
"""
print(query)
p = obj.fetch_query(query)
print("Query Result", p)
for i in p:
print("Result[0] : ", i[0])
print("Result : ", p)
i = i[0]
j = i
approve_url = f"http://127.0.0.1:8000/form/test?request_id={i}"
print("Url : ", approve_url)
try:
send_mail(
'KSA Test Activation',
approve_url,
'Noreplygcontrol#airlinq.com',
['sorav.parmar#airlinq.com'],
fail_silently=False,
)
except Exception as e:
print("Error : ", e)
except Exception as e:
print("Error : ", e)
request.session['ids'] = ids
request.session['approve_url'] = approve_url
print('Request ID Sent : ', ids)
print('Approve Url Sent : ', approve_url)
form = InputForm()
else:
form = InputForm()
return render(request, 'home.html', {'form': form})
Here is test function where approve_url getting from session variable and put into UI, but res value change in previous data as well.Its not same as request_id in approve_url.
the latest request id is overwrite in previous as well.
#api_view(['GET', 'POST'])
def test(request):
ids = request.session.get('ids')
print("Git ID from Index View : ", ids)
if 'approve_url' in request.session:
s = request.session['approve_url']
print(s)
res = s.split('=')[1]
print(res)
if request.method == "POST":
form = TestForm(request.POST)
url = s
url_req = url.split('=')[1]
# rq = request_id["request_id"]
s = sql()
query = f"""update request_form_db.request_form_mymodel
set is_approved=1
where request_id = '{url_req}' """
print(query)
s.update_query(query)
print("Updated Successfully")
form = TestForm()
else:
form = TestForm()
context = {'form': form, 'res': res, }
return render(request, 'test.html', context)
Here is test.html code where value of res
<form action ="{% url 'test' %}" method="POST">
<div class="form_data">
{% csrf_token %}
<br><br>
{{form.myfield}}
<br><br>
<label><b>Request Id</b></label> {{res}}<br>
<input type="submit" value="Submit" class="btn btn-success" />
Below both screenshots of request id overwrites in previous data, I want to different request id is setting on different approve_url.
latest url code
previous data that request id is overwrite

Form Validation not happening for Django model form

I have created the following model form and I want to apply validation on it but it is not working. Can anyone please tell me what mistake I am making?
"""class used for booking a time slot."""
class BookingForm(forms.ModelForm):
class Meta:
model = Booking
fields = ['check_in_date', 'check_in_time', 'check_out_time',
'person', 'no_of_rooms']
"""Function to check if username and password match or not."""
def clean(self):
cleaned_data = super().clean()
normal_book_date = cleaned_data.get("check_in_date")
normal_check_in = cleaned_data.get("check_in_time")
if (normal_book_date < now.date() or
(normal_book_date == now.date() and
normal_check_in < now.time())):
#self._errors['check_in_date'] = self.error_class([
# 'You can only book for future.])
raise ValidationError(
"You can only book for future."
)
return cleaned_data
Edit:
Here is the template that I am rendering. I want to show the error in the template itself. Like how real forms work and show errror.
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Booking</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="{% static 'hotel/css/base.css' %}">
<style>
*{
padding: 0;
margin: 0;
}
</style>
</head>
<body id="body-color">
<div class="container2" id="boxx">
<h2 class="w3-center">Room Slot Booking</h2><br/>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" class= "submit submit-right" value="Search Availability" />
</form>
<br/>
</div>
</body>
</html>
Here is the views.py file
"""Function to return the available categories."""
#login_required(login_url="/hotel/signin/")
def booking(request):
if request.method == 'POST':
form = BookingForm(request.POST)
if form.is_valid():
request.session['normal_book_date'] = request.POST['check_in_date']
normal_book_date = convert_to_date(request.session['normal_book_date'])
request.session['normal_check_in'] = request.POST['check_in_time']
normal_check_in = convert_to_time(request.session['normal_check_in'])
request.session['normal_check_out'] = request.POST['check_out_time']
# now is the date and time on which the user is booking.
if (normal_book_date > now.date() or
(normal_book_date == now.date() and
normal_check_in >= now.time())):
request.session['normal_person'] = int(request.POST['person'])
request.session['normal_no_of_rooms_required'] = int(
request.POST['no_of_rooms']
)
normal_check_out = convert_to_time(request.session['normal_check_out'])
response = list()
response = search_availability(True,
normal_book_date,
normal_check_in,
normal_check_out,
request.session['normal_person'],
request.session['normal_no_of_rooms_required'])
if response:
context = {
'categories': response,
'username': request.session['normal_username']
}
return render(request, 'categories.html', context)
return HttpResponse("Not Available")
else:
context = {
'form': BookingForm(),
'username': request.session['normal_username']
}
return render(request, 'book.html', context)
else:
context = {
'form': BookingForm(),
'username': request.session['normal_username']
}
return render(request, 'book.html', context)
context = {
'form': BookingForm(),
'username': request.session['normal_username']
}
return render(request, 'book.html', context)
Just override the is_valid() instead of the clean.. That's where I've found success
"""class used for booking a time slot."""
class BookingForm(forms.ModelForm):
class Meta:
model = Booking
fields = ['check_in_date', 'check_in_time', 'check_out_time',
'person', 'no_of_rooms']
"""Function to check if username and password match or not."""
def is_valid(self):
valid = super(BookingForm, self).is_valid()
# ^ valid is a Boolean
# Note: added self to cleaned_data.get()
normal_book_date = self.cleaned_data.get("check_in_date")
normal_check_in = self.cleaned_data.get("check_in_time")
if (normal_book_date < now.date() or
(normal_book_date == now.date() and
normal_check_in < now.time())):
valid = False
# Not sure if this works, or is needed (the "raise" part mostly)
# if it doesn't work just add the error to the field instead (see below)
raise ValidationError(
"You can only book for future."
)
# You could also add the error msg per field & it will render it
# - extra tidbit
self.add_error('normal_book_date', 'You can only book for future.')
return valid
That is_valid is called when you do form.is_valid() in the view, so make sure you're doing that too
Edit
Here's how you would pass the failed form to the render. You just pass that form variable instead of init a new BookingForm()
Not only will it show the Errors, but it will keep the fields filled with whatever you submitted (instead of clearing the entire form)
view.py
"""Function to return the available categories."""
#login_required(login_url="/hotel/signin/")
def booking(request):
if request.method == 'POST':
form = BookingForm(request.POST)
if form.is_valid():
request.session['normal_book_date'] = request.POST['check_in_date']
normal_book_date = convert_to_date(request.session['normal_book_date'])
request.session['normal_check_in'] = request.POST['check_in_time']
normal_check_in = convert_to_time(request.session['normal_check_in'])
request.session['normal_check_out'] = request.POST['check_out_time']
# This should be in the form.is_valid() & removes an else
#
# now is the date and time on which the user is booking.
# if (normal_book_date > now.date() or
# (normal_book_date == now.date() and
# normal_check_in >= now.time())):
request.session['normal_person'] = int(request.POST['person'])
request.session['normal_no_of_rooms_required'] = int(
request.POST['no_of_rooms']
)
normal_check_out = convert_to_time(request.session['normal_check_out'])
response = list()
response = search_availability(True,
normal_book_date,
normal_check_in,
normal_check_out,
request.session['normal_person'],
request.session['normal_no_of_rooms_required'])
if response:
# Success!
context = {
'categories': response,
'username': request.session['normal_username']
}
return render(request, 'categories.html', context)
# no availability
return HttpResponse("Not Available")
else:
context = {
'form': form, # <- pass the failed form to the render
'username': request.session['normal_username']
}
return render(request, 'book.html', context)
context = {
'form': BookingForm(),
'username': request.session['normal_username']
}
return render(request, 'book.html', context)
To really clean it up and remove some extra else you could only use a single form variable
view.py (condensed)
"""Function to return the available categories."""
#login_required(login_url="/hotel/signin/")
def booking(request):
# Init the form - This will either:
# a) init a new form (if no POST)
# b) fill form with POST data
form = BookingForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
request.session['normal_book_date'] = request.POST['check_in_date']
normal_book_date = convert_to_date(request.session['normal_book_date'])
request.session['normal_check_in'] = request.POST['check_in_time']
normal_check_in = convert_to_time(request.session['normal_check_in'])
request.session['normal_check_out'] = request.POST['check_out_time']
request.session['normal_person'] = int(request.POST['person'])
request.session['normal_no_of_rooms_required'] = int(
request.POST['no_of_rooms']
)
normal_check_out = convert_to_time(request.session['normal_check_out'])
response = list()
response = search_availability(True,
normal_book_date,
normal_check_in,
normal_check_out,
request.session['normal_person'],
request.session['normal_no_of_rooms_required'])
if response:
# Success!
context = {
'categories': response,
'username': request.session['normal_username']
}
return render(request, 'categories.html', context)
# no availability
return HttpResponse("Not Available")
# Implied else, form failed is_valid and `form` now has the .errors attribute
# (will render the page with it)
context = {
'form': form,
'username': request.session['normal_username']
}
return render(request, 'book.html', context)

Error message: Employee matching query does not exist

I have model Employee and same table in my local database. I need to have the possibility to edit any record and save it locally. When I have something in the webflow_id field I got this error when I tried to select the edit option: Employee matching query does not exist.
When I tried to edit record without this webflow_id it doesn't change, but creates a new record.
my views.py:
def staff_edit(request, webflow_id):
#employees = Employee.objects.all()
#print(employees)
if request.method == 'GET':
if webflow_id == 0:
form = EmployeeEditForm()
else:
try:
#employees = Employee.objects.get(pk=webflow_id)
employees = Employee.objects.get(pk=webflow_id)
except Employee.DoesNotExist:
raise Http404("Employee DoesNotExist")
form = EmployeeEditForm(instance=employees)
return render(request, 'staffedit.html', {'form': form})
else:
if webflow_id == 0:
form = EmployeeEditForm(request.POST)
else:
employees = Employee.objects.get(pk=webflow_id)
form = EmployeeEditForm(request.POST, instance=employees)
if form.is_valid():
form.save()
return redirect('feedback:staff')
context = {'form': form} #when the form is invalid
return render(request, 'staffedit.html', context)
models.py:
class Employee(models.Model):
webflow_id = models.CharField(max_length=100, primary_key=True, default=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100, default=True)
email = models.EmailField(max_length=100)
user_type = models.CharField(max_length=100)
status = models.CharField(max_length=100, default=True)
roles = models.ManyToManyField('Role', through='EmployeeRole')
def __str__(self):
return self.webflow_id + " " + self.email + " " + self.first_name + " " + self.last_name
this is my general html staff.html:
$(document).ready(function() {
var data;
fetch("http://192.168.2.85:8000/fetchapi_employees/")
.then(response => response.json())
.then(json => data = json)
.then(() => {console.log(data); //this gave me Array of objects from my database
$('#datatable').DataTable( {
data: data.employees,
deferRender: true,
scrollY: false,
scrollX: false,
scrollCollapse: true,
scroller: true,
"columns": [
{ data: "webflow_id" },
{ data: "first_name" },
{ data: "last_name" },
{ data: "email" },
{ render: function ( data, type, row ) {
return '<i class="far fa-edit fa-lg" aria-hidden="true"></i>';
} },
{ render: function ( data, type, row ) {
return '<i class="fa fa-plus-circle" aria-hidden="true"></i>';
} },
],
"order": [[1, 'asc']]
} )
})
} );
staffedit.html:
<div class="container">
<div class="col-md-10.offset-md-1 mt-5">
<div class="jumbotron">
<h1 class="display-4">Edit employee</h1>
<hr class="my-4">
<form action="" method="post" autocomplete="off">
{% csrf_token %}
{{form.as_p}}
<button type="submit" class="btn btn-success"><i class="far fa-save"></i> Save</button>
</form>
</div>
</div>
</div>
forms.py:
class EmployeeEditForm(ModelForm):
class Meta:
model = Employee
fields = [
'webflow_id',
'first_name',
'last_name',
'roles',
]
and this is my urls.py:
path('staff/edit/<int:webflow_id>', views.staff_edit, name="staffedit"),
Can anyone see what I'm missing?
Best regards!
webflow_id is a CharField
webflow_id = models.CharField(max_length=100, default=True)
Url parameter must be contain string:
path('staff/edit/<str:webflow_id>', views.staff_edit, name="staffedit"),
Also your webflow_id is not primary key. If you want to use it as primary key, you have to add primary_key=True.
webflow_id = models.CharField(max_length=100, primary_key=True)
I would also use Try Except for get method:
from django.http import Http404
try:
Employee.objects.get(webflow_id=webflow_id)
except Employee.DoesNotExist:
raise Http404("Employee DoesNotExist")

How to access child model from parent model in Python

I am trying to get data from child model through the parent model, I don't know if it possible or there is a way of doing it, and I want to know how to implement the formset concept in this context , I would be grateful for any solution
models.py
class Client_Data(models.Model):
RC = models.CharField(max_length=50)
Raison_social = models.CharField(max_length=254)
NIF = models.CharField(max_length=50,unique=True)
AI = models.CharField(max_length=50,unique=True)
NIS = models.CharField(max_length=50,unique=True)
Banque = models.CharField(max_length=50,unique=True)
CB = models.CharField(max_length=50)
adresse = models.CharField(max_length=50)
slug = models.SlugField(blank=True, unique=True)
active = models.BooleanField(default=True)
class Contact(models.Model):
client = models.ForeignKey(Client_Data,blank=True,on_delete=models.CASCADE)
Nom = models.CharField(max_length=50)
post = models.CharField(max_length=50)
Tel = models.CharField(max_length=50)
email = models.EmailField(max_length=255,unique=True)
contact_type = models.CharField(default='Client_contact',max_length=50)
views.py
def save_client_form(request, form,Contact_form, template_name):
data = dict()
if request.method == 'POST':
if form.is_valid() and Contact_form.is_valid():
client = form.save()
contact = Contact_form.save(commit=False)
contact.client = client
contact.save()
form.save()
Contact_form.save()
data['form_is_valid'] = True
books = Client_Data.objects.all()
data['html_book_list'] = render_to_string('Client_Section/partial_client_c.html', {
'client': books
})
else:
print(form.errors)
print(Contact_form.errors)
data['form_is_valid'] = False
context = {'form': form,'contact_form':Contact_form}
data['html_form'] = render_to_string(template_name, context, request=request)
return JsonResponse(data)
def client_update(request,slug):
book = get_object_or_404(Client_Data, slug=slug)
contact = Contact.objects.select_related().filter(client=book.id)
print(contact)
if request.method == 'POST':
form = ClientForm(request.POST, instance=book)
contact_form = Contact_Form(request.POST, instance=contact)
else:
form = ClientForm(instance=book)
contact_form = Contact_Form(instance=contact)
return save_client_form(request, form,contact_form ,'Client_Section/partial_client_update.html')
If I understand you correctly, you may simply do it this way:
contact = Contact.objects.select_related().filter(client=book.id)
addresse = contact.client.addresse
in you view.py
from django.forms import inlineformset_factory
from django.shortcuts import render, get_object_or_404
def client_update(request, slug):
context = {}
book = get_object_or_404(Client_Data, slug=slug)
formset = inlineformset_factory(Client_Data, Contact, form=Contact_Form )
if request.method == 'POST':
form = ClientForm(request.POST, instance=book)
contactforms = formset(request.POST, prefix='contactformset', instance=book)
context['form'] = form
context['contactforms'] = contactforms
if contactforms.is_valid() and form.is_valid():
form.save()
contactforms.save()
return HttpResponse("your data saved")
else:
return render(request, 'Client_Section/partial_client_update.html', context)
else:
form = ClientForm(instance=book)
contactforms = formset(prefix='contactformset', instance=book)
context['form'] = form
context['contactforms'] = contactforms
return render(request, 'Client_Section/partial_client_update.html', context)
in partial_client_update.html
<form method="POST">
{% csrf_token %}
{{form}}
<hr>
{% formset in contactforms %}
{{formset }}
<hr>
{% endfor %}
<button type="submit ">update</button>
</form>

Django dynamic forms validation

So I am new to Django and I have created a View which uses a total of 8 forms dynamically. There is one base form which is always displayed and then there are 7 more forms that are displayed only if user selects that option from a drop down (drop down is in the HTML template).
I am now trying to validate the form fields and when I display all 8 forms statically, the validation (clean methods) for each of the forms work perfectly! However when I change that to dynamically display the forms based on user selection, the validation for the base form fails every time.
Any idea why that could be happening? I could provide instances of the forms/view if that would help!
Template:
<form0 id="BaseForm" action="/test_created/" method="post">
{% csrf_token %}
{{create_test_form.as_ul}} <br><br>
</form0>
<form1 id="vc1Form" action="" method="post" style="display:none">
{% csrf_token %}
{{vc1_form.as_ul}} <br><br>
</form1>
<form2 id="vc2Form" action="" method="post" style="display:none">
{% csrf_token %}
{{vc2_form.as_ul}} <br><br>
</form2>
<form3 id="vc3Form" action="" method="post" style="display:none">
{% csrf_token %}
{{vc3_form.as_ul}} <br><br>
</form3>
<form4 id="vc4Form" action="" method="post" style="display:none">
{% csrf_token %}
{{vc4_form.as_ul}} <br><br>
</form4>
<form5 id="vc5Form" action="" method="post" style="display:none">
{% csrf_token %}
{{vc5_form.as_ul}} <br><br>
</form5>
<form6 id="vc6Form" action="" method="post" style="display:none">
{% csrf_token %}
{{vc6_form.as_ul}} <br><br>
</form6>
<form7 id="vc7Form" action="" method="post" style="display:none">
{% csrf_token %}
{{vc7_form.as_ul}} <br><br>
</form7>
<div>
<select id="validation_classes_id" name="all_validation_classes" onchange="showForm()">
<option value="%">Choose the validation class</option>
{% for val_class in all_validation_classes %}
<option value="{{ val_class.id }}">{{ val_class.id}} {{val_class.name }}</option>
{% endfor %}
</select> <br> <br>
<form id="submit" action="" method="post">
{% csrf_token %}
<input type="submit" value="Submit" onclick=""/>
</form>
</div>
<br><br>
<script>
function showForm(){
if (validation_classes_id.value == 1){
console.log("Chose validation class 1");
var div = document.getElementById('vc1Form');
console.log(div)
div.style.display='block';
}
else if (validation_classes_id.value == 2){
console.log("Chose validation class 2");
var div = document.getElementById('vc2Form');
console.log(div)
div.style.display='block';
}
else if (validation_classes_id.value == 3){
console.log("Chose validation class 3");
var div = document.getElementById('vc3Form');
console.log(div)
div.style.display='block';
}
else if (validation_classes_id.value == 4){
console.log("Chose validation class 4");
var div = document.getElementById('vc4Form');
console.log(div)
div.style.display='block';
}
else if (validation_classes_id.value == 5){
console.log("Chose validation class 5");
var div = document.getElementById('vc5Form');
console.log(div)
div.style.display='block';
}
else if (validation_classes_id.value == 6){
console.log("Chose validation class 6");
var div = document.getElementById('vc6Form');
console.log(div)
div.style.display='block';
}
else if (validation_classes_id.value == 7){
console.log("Chose validation class 7");
var div = document.getElementById('vc7Form');
console.log(div)
div.style.display='block';
}
}
</script>
View:
def create_test(request):
context = {
'all_validation_classes': ValidationClass.objects.all(),
'create_test_form': CreateTestForm,
'vc1_form': VC1Form,
'vc2_form': VC2Form,
'vc3_form': VC3Form,
'vc4_form': VC4Form,
'vc5_form': VC5Form,
'vc6_form': VC6Form,
'vc7_form': VC7Form
}
if request.method == 'POST':
create_test_form = CreateTestForm(request.POST)
vc1_form = VC1Form(request.POST)
vc2_form = VC2Form(request.POST)
vc3_form = VC3Form(request.POST)
vc4_form = VC4Form(request.POST)
vc5_form = VC5Form(request.POST)
vc6_form = VC6Form(request.POST)
vc7_form = VC7Form(request.POST)
if create_test_form.is_valid():
print("This is where I am")
print("Create Test form looks valid")
vc_list = request.POST.getlist('validation_class', None)
selected_vc = ValidationClass.objects.filter(pk__in=vc_list)
global_val_class = selected_vc
if vc1_form.is_valid():
print("VC1Form is valid")
else:
print("Failing at VC1")
return HttpResponseRedirect('/test_not_created/')
if vc2_form.is_valid():
print("VC2Form is valid")
else:
print("Failing at VC2")
return HttpResponseRedirect('/test_not_created/')
if vc3_form.is_valid():
print("VC3Form is valid")
else:
print("Failing at VC3")
return HttpResponseRedirect('/test_not_created/')
if vc4_form.is_valid():
print("VC4Form is valid")
else:
print("Failing at VC4")
return HttpResponseRedirect('/test_not_created/')
if vc5_form.is_valid():
print("VC5Form is valid")
else:
print("Failing at VC5")
return HttpResponseRedirect('/test_not_created/')
if vc6_form.is_valid():
print("VC6Form is valid")
else:
print("Failing at VC6")
return HttpResponseRedirect('/test_not_created/')
if vc7_form.is_valid():
print("VC7Form is valid")
else:
print("Failing at VC7")
return HttpResponseRedirect('/test_not_created/')
return HttpResponseRedirect('/test_created/')
else:
print("Failing at create_test")
return HttpResponseRedirect('/test_not_created/')
else:
create_test_form = CreateTestForm()
vc1_form = VC1Form()
vc2_form = VC2Form()
vc3_form = VC3Form()
vc4_form = VC4Form()
vc5_form = VC5Form()
vc6_form = VC6Form()
vc7_form = VC7Form()
return render (request, 'create_test.html', context)
Forms:
class CreateTestForm(forms.ModelForm):
class Meta:
model = Test
fields = ['name', 'test_group', 'description', 'query_text', 'failure_condition', 'status']
def clean_status(self):
print("This is where I am")
print(self.cleaned_data)
def getKey(self):
return "create_test_form"
class VC1Form(forms.Form):
expected_relation = forms.ChoiceField(choices = [('<','<'), ('>','>'), ('=','='), ('<=','<='), ('>=','>='), ('!=','!=')], required = True, label = 'Expected Relation: ')
num_rows = forms.IntegerField(initial = 0)
def getKey(self):
return "vc1_form"
class VC2Form(forms.Form):
expected_relation = forms.ChoiceField(choices=[('<', '<'), ('>', '>'), ('=', '='), ('<=', '<='), ('>=', '>='), ('!=', '!=')], required=True, label='Expected Relation: ')
comparing_value_type = forms.ChoiceField(choices=[('Integer', 'Integer'), ('String', 'String')], required=True, label='Comparing Value Type')
comparing_value = forms.CharField(initial = 0)
def clean_comparing_value(self):
exp_rel = self.cleaned_data['expected_relation']
input_val_type = self.cleaned_data['comparing_value_type']
input_val = self.cleaned_data['comparing_value']
if (input_val_type == 'Integer'):
print("I am in integer")
try:
int(input_val)
print(int(input_val))
return input_val
except ValueError:
print("Getting a value error")
raise forms.ValidationError('Should be an Integer')
elif (input_val_type == 'String'):
print("I am in string")
if (exp_rel != '!=' and exp_rel != '='):
print("I am in here...")
raise forms.ValidationError('Must have either = or != as comparator for String')
try:
int(input_val)
print(int(input_val))
print("getting a value error")
raise forms.ValidationError('Should be a string')
except ValueError:
print("No value error")
return input_val
def getKey(self):
return "vc2_form"
class VC3Form(forms.Form):
comparing_value_2 = forms.CharField(label = 'Comparing Value', initial=" ") #Need to figure out if its needed to make this into an array?
# Not sure for now if there is a need to validate this data
def getKey(self):
return "vc3_form"
class VC4Form(forms.Form):
# # This is mostly not needed as we will only check the values in the first column of the query results (as per documentation)
wanted_value = forms.CharField(label = 'Name of corresponding column', initial=" ") #Need to figure out how the input will be an actual variable from the select query
acceptable_error_rate = forms.IntegerField(min_value = 0, max_value = 100, initial=0)
def getKey(self):
return "vc4_form"
class VC5Form(forms.Form):
expected_relation_2 = forms.ChoiceField(choices=[('<', '<'), ('>', '>'), ('=', '='), ('<=', '<='), ('>=', '>='), ('!=', '!=')], required=True,label='Expected Relation: ')
comparing_value_type_2 = forms.ChoiceField(choices=[('Integer', 'Integer'), ('String', 'String')], required=True, label='Comparing Value Type')
def clean_comparing_value_type_2(self):
expected_relation_choices = ('<', '>', '=', '<=', '>=', '!=')
exp_rel = self.cleaned_data['expected_relation_2']
input_val_type = self.cleaned_data['comparing_value_type_2']
print("This is the input val type")
print(input_val_type)
if (input_val_type == 'String'):
print("I get in here")
if (exp_rel != '=' and exp_rel != '!='):
raise forms.ValidationError('Must have either = or != as comparator for String')
return exp_rel
def getKey(self):
return "vc5_form"
class VC6Form(forms.Form):
expected_relation_3 = forms.ChoiceField(choices=[('<', '<'), ('>', '>'), ('=', '='), ('<=', '<='), ('>=', '>='), ('!=', '!=')], required=True, label='Expected Relation: ')
def getKey(self):
return "vc6_form"
class VC7Form(forms.Form):
expected_relation_one = forms.ChoiceField(choices=[('<', '<'), ('>', '>'), ('=', '='), ('<=', '<='), ('>=', '>='), ('!=', '!=')], required=True, label='Expected Relation to First Value: ')
comparing_value_one = forms.IntegerField(label = 'First comparing value', initial=0)
expected_relation_two = forms.ChoiceField(choices=[('<', '<'), ('>', '>'), ('=', '='), ('<=', '<='), ('>=', '>='), ('!=', '!=')], required=True, label='Expected Relation to Second Value: ')
comparing_value_two = forms.IntegerField(label = 'Second comparing value', initial=0)
def getKey(self):
return "vc7_form"