How to export to XML format from DJango SQLIte - python

I have a table of datasets in a django template like so:
{% extends 'base.html' %}
{% block title %}Catalogs{% endblock %}
{% block content %}
<table class="table table-bordered" id="tblData">
<thead>
<tr>
<th>DatasetName</th>
<th>Type</th>
<th>Classification</th>
<th>OriginalSource</th>
<th>OriginalOwner</th>
<th>YearOfOrigin</th>
</tr>
</thead>
</table>
{% for catalog in object_list %}
<div class="container">
<table class="table table-bordered">
<tbody>
<tr>
<td>
<form>
<p><input type="checkbox" id="agreeCheckbox" name="agreeCheckbox" value="agreeCheckbox" onchange="toggleLink(this);"></p>
</form>
</td>
<td>{{ catalog.DatasetName }}</td>
<td>{{ catalog.Type }}</td>
<td>{{ catalog.Classification }}</td>
<td>{{ catalog.OriginalSource }}</td>
<td>{{ catalog.OriginalOwner }}</td>
<td>{{ catalog.YearOfOrigin }}</td>
</tr>
</tbody>
</table>
</div>
<div class="card-footer text-center text-muted">
Update |
Delete |
Export to XML
</div>
{% endfor %}
{% endblock content %}
I have implemented the check box functionality for each of the rows of the table like so:
function toggleLink(checkBox)
{
var link1 = document.getElementById("agreeLink1");
var link2 = document.getElementById("agreeLink2");
var link3 = document.getElementById("agreeLink3");
if (checkBox.checked)
{
link1.style.display = "inline";
link2.style.display = "inline";
link3.style.display = "inline";
}
else {
link1.style.display = "none";
link2.style.display = "none";
link3.style.display = "none";
}
}
I have a model of datasets like so:
class Catalog(models.Model):
DatasetName = models.CharField(max_length=280)
Type = models.CharField(max_length=280)
Classification = models.CharField(max_length=280)
OriginalSource = models.CharField(max_length=280)
OriginalOwner = models.CharField(max_length=280)
YearofOrigin = models.IntegerField(default=0)
def get_absolute_url(self):
return reverse('catalog_detail', args=[str(self.id)])
def __str__(self):
return self.DatasetName
I have implemented a serializerin the view.py file that exports all the datasets like so:
def export_to_xml(request):
from django.core import serializers
data = serializers.serialize("xml", Catalog.objects.all())
from django.core.files import File
f = open('catalogs.xml', 'w')
myfile = File(f)
myfile.write(data)
myfile.close()
return HttpResponse("All done!")
I want to export only those datasets whose checkboxes have been checked. Each dataset is written as a table with a checkbox. I want to export in XML format only those datasets whose checkbox has been checked. Does anybody have any idea on how to do it?

Something like this.
template
<form>
<p><input type="checkbox" id="agreeCheckbox" name="agreeCheckbox" value="{{catalog.id}}" onchange="toggleLink(this);"></p>
</form>
views.py
def export_to_xml(request):
if request.method == 'POST':
#gives list of id of inputs
list_of_input_ids=request.POST.getlist('agreeCheckbox')
from django.core import serializers
data = serializers.serialize("xml", Catalog.objects.filter(id__in=list_of_input_ids))
from django.core.files import File
f = open('catalogs.xml', 'w')
myfile = File(f)
myfile.write(data)
myfile.close()
return HttpResponse("All done!")

Related

Model Instance Settings || Reverse for '' with arguments '('',)' not found. 1 pattern(s) tried

I currently have an app that is meant to generate documents based on user-set settings. The settings are supposed to be read by the program based on the class's instance settings so that the program knows which setting it is generating documents for.
When creating the instance settings for the user to edit each model entry, the code works like this:
setting = get_object_or_404(SettingsClass, pk=setting_pk)
if request.method == 'GET':
form = SettingUpdateForm(instance=setting)
return render(request, 'main/viewSettings.html', {'setting': setting, 'form':form})
else:
form = SettingUpdateForm(request.POST, instance=setting)
if form.is_valid():
form.save()
return redirect('settingsHome')
So it uses the "get_object_or_404" function to return the instance that the user should be working in and tells the form to use that instance here :form = SettingUpdateForm(instance=setting)
However when I am trying to execute this while reading from the model , the same type of setup does not work. This is what I have set up in my views at the moment:
def printReports(request , reports_pk):
pkForm = get_object_or_404(SettingsClass , pk=reports_pk)
form= SettingsClass(instance=pkForm)
complexName = form.Complex
I am basically trying to tell the program to work in a certain instance of the model and read items from there, like: complexName = form.Complex
If anyone has any solution or alternate way to setup something like this , please assist. I will add the my URLs, templates and views code below for better viewing
Views.py:
def reportsHome(request):
model = SettingsClass.objects.all().order_by('Complex')
content ={'model':model }
return render(request, 'main/reportsHome.html' , content)
def printReports(request , reports_pk):
pkForm = get_object_or_404(SettingsClass , pk=reports_pk)
form= SettingsClass(instance=pkForm)
complexName = form.Complex
#CHECKING TRIAL BALANCE SETTINGS
if form.Trial_balance_Year_to_date == True:
printTrialBalanceYTD = True
### Printing Trial Balance PDF
response = HttpResponse(content_type= 'application/pdf')
response['Content-Disposition']= 'attachment; filename=TrialBalance' + \
str(datetime.now()) + '.pdf'
response['Content-Transfer-Encoding'] = 'binary'
#SQL STATEMENT
baseSelect = 'SELECT '+ op5 + op4 + ' Debit , Credit FROM [?].[dbo].[PostGL] AS genLedger '
xtrbYTD = baseSelect + trbYTD + op1 + op2 + op3 + op6
cursor = cnxn.cursor();
cursor.execute(baseTRBYear, [complexName], [complexName], [complexName], [one_yrs_ago]);
xAll = cursor.fetchall()
cursor.close()
xtrbYTD = []
for row in xtrbYTD:
rdict = {}
rdict["Description"] = row[0]
rdict["Account"] = row[1]
rdict["Debit"] = row[2]
rdict["Credit"] = row[3]
arr_trbYTD.append(rdict)
content = {"arr_trbYTD":arr_trbYTD , 'xCreditTotal':xCreditTotal , 'xDebitTotal':xDebitTotal , 'complexName':complexName , 'openingBalances': openingBalances ,'printZero':printZero}
html_string=render_to_string('main/pdf-trialbalance.html' , content)
html=HTML(string=html_string)
result=html.write_pdf()
with tempfile.NamedTemporaryFile(delete=True) as output:
output.write(result)
output.flush()
output.seek(0)
response.write(output.read())
return response
else:
printTrialBalanceYTD = False
urls.py:
#Reports
path('accConnect' , views.reportsHome, name='reportsHome'),
path('accConnect/printReports/<int:reports_pk>' , views.printReports , name='printReports')
TEMPLATES:
reportsHome.html:
{% block content%}
<h1 style=" text-align: center">Reports</h1>
<hr>
<br>
<div class="list-group">
<a href="#" class='list-group-item active'>Print Single Complex's</a>
{% for x in model %}
<a href="{% url 'printReports' %}" class="list-group-item list-group-item-action" >{{ x.Complex }} Reports</a>
{% endfor %}
</div>
{% endblock %}
pdf-trialbalance.html:
{% block content%}
<h1 class = 'center'>Kyle Database Trial Balance</h1>
<br>
</div>
<br>
<br>
<div class="table-container">
<table style="width: 100%">
<th >Account</th>
<th>Description</th>
<th>Debit</th>
<th>Credit</th>
{% for arr_trbYTD in arr_trbYTD %}
<tr>
<td>{{ arr_trbYTD.Description }}</td>
<td>{{ arr_trbYTD.Account }}</td>
<td>
{%if arr_trbYTD.Debit > 0%}
{{arr_trbYTD.Debit}}
{%endif%}
</td>
<td>
{%if arr_trbYTD.Credit > 0%}
{{arr_trbYTD.Credit}}
{%endif%}
</td>
</tr>
<tr >
{% endfor %}
<td> <b>Totals</b> </td>
<td> </td>
{% for xDebitTotal in xDebitTotal %}
<td><b>R {{ xDebitTotal }}</b></td>
{% endfor %}
{% for xCreditTotal in xCreditTotal %}
<td><b>R {{ xCreditTotal }}</b></td>
{% endfor %}
</tr>
</table>
</div>
<br>
<br>
<br>
{% endblock %}
To solve the error in the title, first you need to fix the usage of url in the template and pass the primary key of the SettingsClass instance with:
{% url 'printReports' x.pk %}
So:
{% for x in model %}
<a href="{% url 'printReports' x.pk %}" class="list-group-item list-group-item-action" >{{ x.Complex }} Reports</a>
{% endfor %}
And then in your view, you don't need to use a form to access the attributes from your SettingsClass instance, so you can just do something like:
def printReports(request , reports_pk):
settings_instance = get_object_or_404(SettingsClass , pk=reports_pk)
complexName = settings_instance.Complex
#CHECKING TRIAL BALANCE SETTINGS
if settings_instance.Trial_balance_Year_to_date == True:
...
You are not passing the "reports" variable to context. that's why the PK value is empty. check the view that's rendering reportsHome.html and apply the necessary, variable to template eg:
def view_func(request)
......
return render(request, '<template_name>.html', {"report": report })

show a list of fields based on selection first field

I have 2 classes and I´d like to show a list of fields from the second class based on the first class. For example:
servico:
id desc_servico
1 teste1
2 teste2
itemservico:
id desc_itemservico servico
1 itemteste1 1
2 itemteste2 2
In this example, if I choose servico=1, the itemservico has to show me itemteste1. If I choose servico=2, the itemservico has to show itemteste2.
Models.py:
class servico(models.Model):
desc_servico = models.CharField('Descrição', max_length=50, default='', blank=False, null=False)
class itemservico(models.Model):
desc_itemservico = models.CharField('Descrição', max_length=50, default='', blank=False, null=False)
val_itemservico = models.DecimalField(max_digits=8, decimal_places=2)
servico = models.ForeignKey(servico, default='', blank=True, null=True) # Chave estrangeira da Classe Serviço
ind_selecionado = models.BooleanField(default=False)
forms.py:
class itemservicoForm(forms.ModelForm):
servico = forms.ModelChoiceField(queryset=servico.objects.all().order_by('desc_servico'), empty_label="Serviço")
class Meta:
model = itemservico
fields = (
'servico',
)
template.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ORÇAMENTO</title>
</head>
<body>
<h2>ORÇAMENTO</h2>
<form class=" bd-form-20 " action="" name="form-name" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<label class="bd-form-label" >Serviço </label>{{form.servico}}<br><br>
<p><h1>{{form.servivo.id}}</h1></p>
<div class=" bd-customhtml-29 bd-tagstyles bd-custom-table">
<div class="bd-container-inner bd-content-element">
<table border="1" rules="all" cellspacing="0" cellpadding="10">
<tbody>
<tr>
<th>Testar</th>
<th>Selecionar</th>
<th>ID Item Serviço</th>
<th>Item Serviço</th>
<th>Valor Serviço</th>
<th>Serviço</th>
</tr>
{% for item in instance_itens %}
<tr>
<td> <input type="checkbox" id="item.ind_selecionado"></td>
<td>{{ item.ind_selecionado }}</td>
<td>{{ item.id }}</td>
<td>{{ item.desc_itemservico }}</td>
<td>{{ item.val_itemservico }}</td>
<td>{{ item.servico_id}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</form>
<br><br>
<button class="bd-linkbutton-60 bd-button bd-own-margins bd-content-element" type = "submit" >
OK</button>
</body>
</html>
I think you need to use Ajax post for generating results based on selection.
for view.py part you need use this function:
def ajax_post(request):
if request.POST:
if request.POST.get('servico') and request.is_ajax():
itemservico_list = itemservico.objects.filter(servico = request.POST.get('servico'))
return render_to_response('itemservico.html',{'itemservico_list':itemservico_list})
For Html part you need to generate itemservico.html seperated and include it to main html such as
<form method="post">{% csrf_token %}
<tbody><tr>
<th>Testar</th>
<th>Selecionar</th>
<th>ID Item Serviço</th>
<th>Item Serviço</th>
<th>Valor Serviço</th>
<th id='targetselection'>Serviço</th>
</tr>
<div id='inner'>
{% include "itemservico.html" %}
</div>
</tbody>
</form>
And you need to create another html file for itemservico such as
{% for item in itemservico_list %}
<tr>
<td> <input type="checkbox" id="item.ind_selecionado"></td>
<td>{{ item.ind_selecionado }}</td>
<td>{{ item.id }}</td>
<td>{{ item.desc_itemservico }}</td>
<td>{{ item.val_itemservico }}</td>
<td>{{ item.servico_id}}</td>
</tr>
{% endfor %}
For JS part you need to create a js file for which detect state changes or key press of any given field: (I use jquery for selection)
$('#targetselection').on('change keyup paste', function() {
servico = $(this).val() // get the current value of the input field.
ajaxPost(servico);
});
function ajaxPost(query){
$.ajax({
type:"POST",
url:'',
data: {
csrfmiddlewaretoken:token,
servico : servico
},
dataType:'html',
success:function (data,textStatus,jqXHR){
$('#inner').html(data);
}
});
}
As a summary: When some selection changes on the web site, its creating an ajax request on server. As a view part you are filtering data according to ajax post request. Rendering html file and pushing it into specific part of web page. I hope this would be helpfull

How can I show daily schedules of all users in Django?

I'm using Django to make a website for gym trainers.
what I want is a template for the daily schedules of all trainers like this
But, my page is
The problem is the 'td' of per trainer's tr repeats as many as the number of schedules the trainer has. I know the {% for sc in schedules %} is the problem. But, because schedules are the query set, I should use the for and while using for, I should check the right time to insert the schedule to the right tr, td position. How can I make the successful table to show the daily schedules of all users(trainers)?? Anybody will be very helpful to me.
Schedule.model
class Schedule(models.Model):
Trainer = models.ForeignKey(settings.AUTH_USER_MODEL,blank=True,null=True, related_name='schedule', on_delete=models.SET_NULL)
title = models.CharField(max_length=12,blank=True,)
start = models.DateTimeField(null=True, blank=True)
my views.py
def staff_daily_schedule_search(request):
all_schedules = Schedule.objects.all()
Fitness_list = User.objects.filter(groups__name='Fitness') # Fitness Trainers
search_date1 = request.GET.get('search_date','')
search_date= datetime.datetime.strptime(search_date1, '%Y-%m-%d') #%T = %H:%M:%S '%Y-%m-%d'
schedules= Schedule.objects.none()
for f in Fitness_list:
sc = f.schedule.filter(start__year=search_date.year).filter(start__month = search_date.month).filter(start__day = search_date.day)
print(sc)
schedules |= sc
context = {
'search_date' : search_date1 if search_date1 else datetime.date.today(),
'Fitness_list':Fitness_list,
'schedules' : schedules,
}
return render(request, 'management/staff_daily_schedule.html', context)
staff_daily_schedule.html
<form action="{% url 'management:staff_daily_schedule_search' %}" method="GET">
<span><input type="date" class="search_date my-control" name="search_date" value="{{ search_date }}" ></span>
<a id="today" class="btn btn-warning">오늘</a>
<button class="btn btn-info" value="검색" >검색</button>
</form>
<table class="table table-bordered">
<thead>
<tr>
<th></th>
<th>06:00 </th>
<th>07:00 ~ 07:50</th>
<th>08:00 ~ 08:50</th>
<th>09:00 ~ 09:50</th>
<th>10:00 ~ 10:50</th>
</tr>
</thead>
<tbody>
{% for trainer in Fitness_list %}
<tr>
<td>{{ trainer }} </td>
{% for sc in schedules %} <!-- because of this for, td repeats as many as the number of schedule per trainer has..-->
{% if sc.Trainer == trainer %}
{% if sc.start.hour == 21 %} <!--HOUR of 6:00 a.m = 21-->
<td>{{ sc }}</td>
{% else %}
<td ></td>
{% endif %}
{% if sc.start.hour == 22 %}
<td>{{ sc }}</td>
{% else %}
<td ></td>
{% endif %}
{% if sc.start.hour == 23 %}
<td>{{ sc }}</td>
{% else %}
<td ></td>
{% endif %}
{% if sc.start.hour == 0 %} <!-- 9 a.m. -->
<td>{{ sc }}</td>
{% else %}
<td></td>
{% endif %}
{% if sc.start.hour == 1 %}
<td>{{ sc }}</td>
{% else %}
<td></td>
{% endif %}
{% endif %}
{% endfor %}
</tr>
{% endfor %} <!-- tr repetition as trainers number-->
</tbody>
</table>
The problem
If you put the logic in your view instead of the template, it's easy to set up the table exactly like you want it.
[Edited to use an OrderedDict to preserve the order of trainers.]
views.py
def staff_daily_schedule_search(request):
Fitness_list = User.objects.filter(groups__name='Fitness') # Fitness Trainers
search_date1 = request.GET.get('search_date','')
search_date= datetime.datetime.strptime(search_date1, '%Y-%m-%d') #%T = %H:%M:%S '%Y-%m-%d'
trainer_dict = OrderedDict()
# Initialize each row of the table with the trainer's name and a blank schedule
for f in Fitness_list:
trainer_dict[str(f.id)] = {'name': f.get_full_name(), 'hour_21': '',
'hour_22': '', 'hour_23': '', 'hour_0': '', 'hour_1': ''}
schedules = Schedule.objects.filter(start__year=search_date.year).filter(start__month =
search_date.month).filter(start__day = search_date.day)
# Insert each schedule item into the appropriate table row and cell
for sc in schedules:
trainer_dict[str(sc.Trainer.id)]['hour_' + str(sc.start.hour)] = sc.title
context = {
'search_date' : search_date1 if search_date1 else datetime.date.today(),
'trainer_dict': trainer_dict
}
return render(request, 'management/staff_daily_schedule.html', context)
staff_daily_schedule.html
<form action="{% url 'management:staff_daily_schedule_search' %}" method="GET">
<span><input type="date" class="search_date my-control" name="search_date" value="{{ search_date }}" ></span>
<a id="today" class="btn btn-warning">오늘</a>
<button class="btn btn-info" value="검색" >검색</button>
</form>
<table class="table table-bordered">
<thead>
<tr>
<th></th>
<th>06:00 </th>
<th>07:00 ~ 07:50</th>
<th>08:00 ~ 08:50</th>
<th>09:00 ~ 09:50</th>
<th>10:00 ~ 10:50</th>
</tr>
</thead>
<tbody>
{% for trainer in trainer_dict %}
<tr>
<td>{{ trainer.name }}</td>
<td>{{ trainer.hour_21 }}</td>
<td>{{ trainer.hour_22 }}</td>
<td>{{ trainer.hour_23 }}</td>
<td>{{ trainer.hour_0 }}</td>
<td>{{ trainer.hour_1 }}</td>
</tr>
{% endfor %}
</tbody>
</table>

Using queryset to 'filter' within form to display results from DB depending on option selected

I'm trying to develop a view that has a list of records. Within that view is a 'filter' box I'd like to use so that when users select 'HK' or 'JP' as a location. It only displays records submitted for 'HK' or 'JP' depending on whats been selected > Submitted.
I have the layout working, but whenever I'm submitting a new 'filter' option, this returns all results no matter what.
Can anyone provide some insight? I suspect the problem lies in the views context, but I am just stuck.
views.py
def CLIENT_Overtime_Results(request):
overtime_data = Overtime.objects.all()
location = None
if request.method == 'POST':
form = OvertimeForm(data=request.POST)
if form.is_valid():
location = form.data['location']
overtimeid = Location.objects.all()
#overtime_period = Overtime.objects.filter(
else:
form = OvertimeForm()
template_name = "overtime/UBS_Overtime_Results.html"
context = {
'form': form,
'location': location,
'overtime_data': overtime_data,
}
return render(request, template_name, context)
Forms.py
class OvertimeForm(forms.ModelForm):
location = forms.ModelChoiceField(
queryset=Location.objects.all(),
widget=forms.Select(attrs={'class': 'form-control'}))
class Meta:
model = Overtime
fields = ['location']
Filter button/options referenced in 'col-md-3'
HTML
<div class="row">
<form method="POST">
{% csrf_token %}
<div class="col-md-3">{{ form.location }}</div>
<div class="col-md-3">
<button type="submit" class="btn btn-default">{% trans "Filter" %}</button>
</div>
<div class="col-md-6">
<button type="submit" class="btn btn-default pull-right m-left-5" name="pdf">{% trans "PDF Report" %}</button>
<button type="submit" class="btn btn-default pull-right" name="excel">{% trans "Excel Report" %}</button>
</div>
</form>
</div>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>{% trans "ID" %}</th>
<th>{% trans "Date" %}</th>
{% if not location %}
<th>{% trans "Location" %}</th>
{% endif %}
<th>{% trans "Employee Name" %}</th>
<th>{% trans "Client" %}</th>
<th>{% trans "Hours" %}</th>
<th>{% trans "Overtime Type" %}</th>
<th>{% trans "Billable Type" %}</th>
<th>{% trans "Approval" %}</th>
</tr>
</thead>
<tbody>
{% for od in overtime_data %}
<tr>
<td>{{ od.overtime_ID }} </td>
<td>{{ od.overtimeDateStart }}</td>
{% if not location %}
<td>{{ od.location }}</td>
{% endif %}
<td>{{ od.employee }}</td>
<td>{{ od.client }} </td>
<td>{{ od.hours }} </td>
<td>{{ od.overtime_type }}</td>
<td>{{ od.billable_type }}</td>
<td>{{ od.approval|linebreaksbr }}</td>
</tr>
{% empty %}
<tr>
<td colspan="9" class="text-center">{% trans "No overtime history." %}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
This is how the page looks right now: http://imgur.com/ZjKzWMA
Answering my own question for future people coming to this page! As recommended by Daniel Roseman. I needed to include a filtering in the form.is_valid(): argument.
I added the following to my code:
overtime_data = Overtime.objects.filter(location=location)
This essentially filters and matches based on the updated location matching the location field in my model.
Updated code looks like this:
def CLIENT_Overtime_Results(request):
overtime_data = Overtime.objects.all()
location = None
if request.method == 'POST':
form = OvertimeForm(data=request.POST)
if form.is_valid():
location = form.data['location']
overtimeid = Location.objects.all()
overtime_data = Overtime.objects.filter(location=location) #Added for filtering*
else:
form = OvertimeForm()
template_name = "overtime/UBS_Overtime_Results.html"
context = {
'form': form,
'location': location,
'overtime_data': overtime_data,
}
return render(request, template_name, context)

flask wtform field data disappearingappend_entry

Please help - does flask/wtforms somehow treat the data property of a field differently after an append_entry call or am I just really doing this wrong?
I have a form that gets its data from a yaml file. On the initial GET request, the form populates showing the icons from the {% if ifc.poe.data %} as expected. If either button is hit to add a module or interface, the POST re-renders the page, but now ifc.poe.data is empty and thus no icons are rendered. If you comment out the if ifc.xxx.data portion and uncomment out the actual fields, the fields are rendered with the proper data every time. Is this something with how I'm building the form class or in how I'm handling the POST? What happened to the ifc.xxx.data?
Any help is appreciated, I'm pretty new at this.
forms.py
from flask_wtf import Form
from wtforms import Form as wtfForm # Bad hack to get around csrf in fieldlist
class DevInterface(wtfForm):
e_regex = '^ae(\d+)$'
ifc = StringField("Interface", validators=[DataRequired()])
poe = BooleanField('PoE', validators=[Optional()], default=False)
uplink = BooleanField('Uplink', validators=[Optional()],default=False)
desc = StringField("Description", validators=[Optional()],default='')
voip = StringField("VOIP", validators=[Optional()], default='')
etheropt = StringField("LAG interface", validators=[Optional(),Regexp(e_regex, message='Must designate an ae interface, eg. ae4')])
class DevHardware(wtfForm):
module = SelectField('Module', choices=[
('ex2200-24p','ex2200-24p'),('ex2200-48p','ex2200-48p'),
('ex4200-10g','ex4200-10g'),('ex4200-24f','ex4200-24f')],
default='ex2200-48p')
fpc = SelectField('FPC', choices=[(str(i),str(i)) for i in range(10)], default=0)
class DevOptions():
id = StringField('Device Serial Number', validators=[DataRequired()])
hostname = StringField('Hostname', validators=[DataRequired()])
make = SelectField('Make', choices=[('juniper','Juniper')], default = 'juniper')
class AddDev(Form, DevOptions):
modules = FieldList(FormField(DevHardware), min_entries=1)
interfaces = FieldList(FormField(DevInterface), min_entries=1)
add_ifc = SubmitField()
add_module = SubmitField()
views.py
#app.route('/editdev/<vspc>/<dev>', methods=['GET','POST'])
def editdev(vspc,dev):
from skynet.forms import AddDev
try:
d = s.loaddev(dev)
except IOError as e:
flash(dev + ' does not exist.', category='danger')
return redirect(url_for('editvspc', vspc=vspc))
# Have to change up how the data is presented for the form
d['id'] = dev
ifcs = d['interfaces']
del d['interfaces']
l = []
for i in ifcs:
j={}
j['ifc'] = i
j.update(ifcs[i])
l.append(j)
d['interfaces'] = sorted(l, key=lambda k: k['ifc'])
form = AddDev(request.form, data=d)
if form.add_ifc.data:
form.interfaces.append_entry()
elif form.add_module.data:
form.modules.append_entry()
elif request.method == 'POST' and form.validate():
# Placeholder for now
print 'Updated device'
for error in form.errors:
for e in form[error].errors:
flash(e, category='danger')
return render_template('adddev.html', form=form)
template
{% extends "layout.html" %}
{% import "bootstrap/utils.html" as util %}
{% block content %}
{{ super() }}
<div class="container-fluid">
<h1 align='center'>Add Device</h1>
<form method="post" action="">
{{ form.hidden_tag() }}
<div class="form-group">
<table class="table">
<tbody>
<tr>
<td>{{ form.id.label }}</td>
<td>{{ form.id(size=20) }}</td>
</tr>
<tr>
<td>{{ form.hostname.label }}</td>
<td>{{ form.hostname(size=20) }}</td>
</tr>
<tr>
<td>{{ form.make.label }}</td>
<td>{{ form.make}}</td>
</tr>
</tbody>
</table>
{{ form.add_module }}
<table class="table">
<tbody>
{% for field in form.modules.entries %}
<tr>
<td>{{ field.module.label }}</td>
<td>{{ field.module }}</td>
<td>{{ field.fpc.label }}</td>
<td>{{ field.fpc }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<table class="table">
<thead>
<tr>
<th>Interface</th>
<th>Description</th>
<th>PoE</th>
<th>VoIP</th>
<th>LAG</th>
<th>Uplink</th>
</tr>
</thead>
<tbody>
{% for ifc in form.interfaces %}
<tr>
<td>{{ ifc.ifc(size=10) }}</td>
<td>{{ ifc.desc }}</td>
<td>
{% if ifc.poe.data %}
{{ util.icon('flash', style='color:red') }}
{% endif %}
{% if ifc.voip.data %}
{{ util.icon('phone-alt', style='color:green') }}
{% endif %}
{% if ifc.etheropt.data %}
<a class="label label-success">{{ ifc.etheropt.data }}</a>
{% endif %}
{% if ifc.uplink.data %}
{{ util.icon('open', style='color:blue') }}
{% endif %}
</td>
{# <td>{{ ifc.poe }}</td>
<td>{{ ifc.voip }}</td>
<td>{{ ifc.etheropt }}</td>
<td>{{ ifc.uplink }}</td> #}
</tr>
{% endfor %}
</tbody>
</table>
{{ form.add_ifc }}
</div>
<button type="submit" class="btn btn-default">Add Device</button>
</form>
</div>
{% endblock %}

Categories