Django inline formset not valid on update - django

My create method works perfectly, but the update does not. It returns one error for each inline as an empty list []
forms.py
StructureFormset = inlineformset_factory(Plan, Structure,
fields = (
'material_type',
'weight',
'thickness',
'provider'
),
extra=0,
can_delete=True
)
TestFormset = inlineformset_factory(Plan, Test,
fields=(
'essay',
'critic',
'spec'
),
extra = 0,
can_delete=True
)
class PlanForm(ModelForm):
class Meta:
model = Plan
fields = (
'format',
'pc',
'revission',
'rev_date',
'client',
'product',
'gp_code',
'code',
'observation',
'continuation',
'dispatch_conditions',
'elaborator',
'reviewer'
)
localized_fields=('rev_date',)
views.py
def editPlan(request, pk):
plan = Plan.objects.get(id = pk)
form = PlanForm(instance = plan)
sformset = StructureFormset(instance=plan)
tformset = TestFormset(instance=plan)
context = {
'form': form,
'sformset': sformset,
'tformset': tformset
}
if request.method == 'POST':
print('----------------------------request----------------------------')
print(request.POST)
form = PlanForm(request.POST, instance = plan)
sformset = StructureFormset(request.POST, instance=plan, prefix='structure')
tformset = TestFormset(request.POST, instance=plan, prefix='test')
if form.is_valid() and sformset.is_valid() and tformset.is_valid():
print('-----------------------is valid-----------------------')
form.save()
instances = sformset.save(commit=False)
for instance in instances:
sformset.save_m2m()
instance.save()
tformset.save()
return redirect('/plans/')
else:#printing errors
print('-----------------------is not valid-----------------------')
print(sformset.total_error_count())
print(sformset.errors)
print(tformset.total_error_count())
print(tformset.errors)
return render(request, 'home/plan_forms.html', context)
template.html
{{ tformset.management_form }}
<table>
<thead>
<tr>
<th>Essay</th>
<th>
<abb title="Critical Variable">Crit.</abb>
</th>
<th>Spec</th>
{% if tformset.instance.pk %}
<th class="text-center px-1 col-1 pb-2">
<i class="material-icons">delete</i>
</th>
{% endif %}
</tr>
</thead>
<tbody id="tform_set">
<!--Test form goes here-->
{% if tformset %}
{% for tt in tformset %}
{% for hidden in tt.hidden_fields %}
{{ hidden }}
{% endfor %}
<tr>
<td>
{{ tt.essay }}
</td>
<td class="px-1 col-1 text-center justify-content-center">
{{ tt.critic }}
</td>
<td>
{{ tt.spec }}
</td>
<td>
{% if tt.instance.pk %}{{ tt.DELETE }}{% endif %}
</td>
</tr>
{% endfor %}
{% endif %}
</tbody>
<tbody id="tempty_form" style="display:none !important;">
<tr>
<td>
{{ tformset.empty_form.essay }}
</td>
<td>
{{ tformset.empty_form.critic }}
</td>
<td>
{{ tformset.empty_form.spec }}
</td>
</tr>
</tbody>
</table>
{{ sformset.management_form }}
<table>
<thead>
<tr>
<th>Material</th>
<th>Weight (g/m²)</th>
<th>Thickness (μ)</th>
<th>Provider</th>
{% if sformset.instance.pk %}
<th class="text-center col-1 px-1 pb-2">
<i class="material-icons">delete</i>
</th>
{% endif %}
</tr>
</thead>
<tbody id="sform_set">
<!--Structure form goes here-->
{% if sformset %}
{% for ss in sformset %}
{% for hidden in ss.hidden_fields %}
{{ hidden }}
{% endfor %}
<tr>
<td>
{{ ss.material_type }}
</td>
<td>
{{ ss.weight }}
</td>
<td>
{{ ss.thickness }}
</td>
<td>
{{ ss.provider }}
</td>
<td>
{% if ss.instance.pk %}{{ ss.DELETE }}{% endif %}
</td>
</tr>
{% endfor %}
{% endif %}
</tbody>
<tbody id="sempty_form" style="display:none !important;">
<tr>
<td>
{{ sformset.empty_form.material_type }}
</td>
<td>
{{ sformset.empty_form.weight }}
</td>
<td>
{{ sformset.empty_form.thickness }}
</td>
<td>
{{ sformset.empty_form.provider }}
</div>
</td>
</tr>
</tbody>
</table>
This is what i get from the prints;
notice the:
`
1
[]
1
[]
` bellow the `is not valid`
[![Print Output](https://i.stack.imgur.com/whRc0.png)](https://i.stack.imgur.com/whRc0.png)

Related

Django - update inline formset not updating

I'm trying to create an update view which has a few inline formset's in it but for some reason I'm seeing 'id: This field is required.' & none of the inline formset values being set when I click the update button. The fields themselves actually have values in them in the template so I'm not sure why the inline formsets would be empty when trying to save.
Models.py
class ProjectUpdateForm(forms.ModelForm):
class Meta:
model = Project
fields = ('name', 'details')
Views.py
class ProjectUpdateView(LoginRequiredMixin, UpdateView):
model = Project
template_name = 'home/project/project_update.html'
context_object_name = "project"
form_class = ProjectUpdateForm
def get_context_data(self, **kwargs):
ReviewChildFormset = inlineformset_factory(
Project, AdoptedBudgetReview, fields=('project', 'review'), can_delete=False, extra=0
)
itemNames = [{'item': item} for item in ['Concept & Feasibility', 'Planning & Design', 'Procurement', 'Delivery & Construction', 'Finalisation']]
EstimatedBudgetChildFormset = inlineformset_factory(
Project, EstimatedBudget, fields=('project', 'item', 'cost', 'time'), can_delete=False, formset=EstimatedInlineFormset, extra=0, widgets={'item': forms.Select(attrs={'disabled': True})},
)
FutureExpenditureFormset = inlineformset_factory(
Project, FutureExpenditure, fields=('project', 'byear', 'internalFunding', 'externalFundingSource', 'externalFunding'), can_delete=False, extra=0,
)
PreviousExpenditureFormset = inlineformset_factory(
Project, PreviousExpenditure, fields=('project', 'byear', 'internalFunding', 'externalFunding'), can_delete=False, extra=0,
)
initial = [{'priority': priority} for priority in Priority.objects.all()]
PriorityChildFormset = inlineformset_factory(
Project, ProjectPriority, fields=('project', 'priority', 'score'), can_delete=False, extra=0, widgets={'priority': forms.Select(attrs={'disabled': True})},
)
context = super().get_context_data(**kwargs)
if self.request.POST:
context['adoptedreviews'] = ReviewChildFormset(self.request.POST, instance=self.object)
context['estimatedbudget'] = EstimatedBudgetChildFormset(self.request.POST, initial=itemNames, instance=self.object)
context['futureexpenditure'] = FutureExpenditureFormset(self.request.POST, instance=self.object)
context['previousexpenditure'] = PreviousExpenditureFormset(self.request.POST, instance=self.object)
context['priorities'] = PriorityChildFormset(self.request.POST, initial=initial, instance=self.object)
else:
context['adoptedreviews'] = ReviewChildFormset(instance=self.object)
context['estimatedbudget'] = EstimatedBudgetChildFormset(initial=itemNames, instance=self.object)
context['futureexpenditure'] = FutureExpenditureFormset(instance=self.object)
context['previousexpenditure'] = PreviousExpenditureFormset(instance=self.object)
context['priorities'] = PriorityChildFormset(initial=initial, instance=self.object)
return context
def form_valid(self, form):
context = self.get_context_data()
adoptedreview = context["adoptedreviews"]
estimatedbudget = context["estimatedbudget"]
prioritycriteria = context["priorities"]
futureexpenditure = context["futureexpenditure"]
previousexpenditure = context["previousexpenditure"]
form.instance.creator = self.request.user
if adoptedreview.is_valid() and estimatedbudget.is_valid() and previousexpenditure.is_valid() and futureexpenditure.is_valid and prioritycriteria.is_valid():
self.object = form.save()
adoptedreview.instance = self.object
estimatedbudget.instance = self.object
futureexpenditure.instance = self.object
previousexpenditure.instance = self.object
prioritycriteria.instance = self.object
adoptedreview.save()
estimatedbudget.save()
previousexpenditure.save()
futureexpenditure.save()
prioritycriteria.save()
else:
return self.form_invalid(form)
return super(ProjectCreateview, self).form_valid(form)
Template
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Update Project</legend>
{{ form|crispy }}
</fieldset>
<h2>Adopted Budget Review</h2>
<!-- {{ adoptedreviews|crispy }} -->
<table class="table table-light">
<thead>
<tr>
<th scope="col"></th>
<th scope="col">BR1</th>
<th scope="col">BR2</th>
<th scope="col">BR3</th>
<th scope="col">BR4</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Amount</th>
{{ adoptedreviews.management_form }}
{% for adrform in adoptedreviews.forms %}
{% for field in adrform.visible_fields %}
<td>
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
{% endfor %}
</tr>
</tbody>
</table>
<h2>Estimated Budget - Breakdown Yr1</h2>
<!-- {{ estimatedbudget|crispy }} -->
<table class="table table-light">
{{ estimatedbudget.management_form }}
<thead>
<tr>
<th scope="col">Item - Description</th>
<th scope="col">Anticipated % cost</th>
<th scope="col">Anticipated time - weeks</th>
</tr>
</thead>
{% for form in estimatedbudget.forms %}
<tr>
<td>
{{ form.errors }}
<h4>{{ form.item.value }}</h4>
{{ form.item.as_hidden }}
</td>
<td>
{{ form.cost }}
</td>
<td>
{{ form.time }}
</td>
</tr>
{% endfor %}
</table>
<h2>Future Project Expenditure</h2>
<!-- {{ futureexpenditure|crispy }} -->
<table class="table table-light">
{{ futureexpenditure.management_form }}
{% for form in futureexpenditure.forms %}
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th scope="col">{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tbody>
<tr class="{% cycle row1 row2 %} formset_row">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
</tbody>
{% endfor %}
</table>
<h2>Previous Project Expenditure</h2>
<table class="table table-light">
<!-- {{ previousexpenditure|crispy }} -->
{{ previousexpenditure.management_form }}
{% for form in previousexpenditure.forms %}
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th scope="col">{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tbody>
<tr class="{% cycle row1 row2 %} previous_formset_row">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
</tbody>
{% endfor %}
</table>
<h2>Priority Criteria</h2>
<!-- {{ priorities|crispy }} -->
<table class="table table-light">
<tbody>
{{ priorities.management_form }}
{% for priority in priorities.forms %}
<tr>
<td>
{{ priority.priority.errors.as_ul }}
{% for value, name in priority.priority.field.choices %}
{% if value == priority.priority.value %}
<h4>{{ name }}</h4>
{% endif %}
{% endfor %}
{{ priority.priority.as_hidden }}
</td>
<td>
{{ priority.score.errors.as_ul }}
{{ priority.score }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Update Project</button>
</div>
</form>
Whenever one renders a forms manually one should remember to always render it's hidden fields, more so for a formset / inlineformset since it automatically adds some hidden fields to the form. Since the formset is updating multiple instances of course there needs to be something present in the formset to indicate which instance is which, which is done by hidden fields here.
Hence you need to render the hidden fields of your formsets forms:
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Update Project</legend>
{{ form|crispy }}
</fieldset>
<h2>Adopted Budget Review</h2>
<!-- {{ adoptedreviews|crispy }} -->
<table class="table table-light">
<thead>
<tr>
<th scope="col"></th>
<th scope="col">BR1</th>
<th scope="col">BR2</th>
<th scope="col">BR3</th>
<th scope="col">BR4</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Amount</th>
{{ adoptedreviews.management_form }}
{% for adrform in adoptedreviews.forms %}
{% for hidden in adrform.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in adrform.visible_fields %}
<td>
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
{% endfor %}
</tr>
</tbody>
</table>
<h2>Estimated Budget - Breakdown Yr1</h2>
<!-- {{ estimatedbudget|crispy }} -->
<table class="table table-light">
{{ estimatedbudget.management_form }}
<thead>
<tr>
<th scope="col">Item - Description</th>
<th scope="col">Anticipated % cost</th>
<th scope="col">Anticipated time - weeks</th>
</tr>
</thead>
{% for form in estimatedbudget.forms %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
<tr>
<td>
{{ form.errors }}
<h4>{{ form.item.value }}</h4>
{{ form.item.as_hidden }}
</td>
<td>
{{ form.cost }}
</td>
<td>
{{ form.time }}
</td>
</tr>
{% endfor %}
</table>
<h2>Future Project Expenditure</h2>
<!-- {{ futureexpenditure|crispy }} -->
<table class="table table-light">
{{ futureexpenditure.management_form }}
{% for form in futureexpenditure.forms %}
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th scope="col">{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tbody>
<tr class="{% cycle row1 row2 %} formset_row">
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
</tbody>
{% endfor %}
</table>
<h2>Previous Project Expenditure</h2>
<table class="table table-light">
<!-- {{ previousexpenditure|crispy }} -->
{{ previousexpenditure.management_form }}
{% for form in previousexpenditure.forms %}
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th scope="col">{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tbody>
<tr class="{% cycle row1 row2 %} previous_formset_row">
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
</tbody>
{% endfor %}
</table>
<h2>Priority Criteria</h2>
<!-- {{ priorities|crispy }} -->
<table class="table table-light">
<tbody>
{{ priorities.management_form }}
{% for priority in priorities.forms %}
{% for hidden in priority.hidden_fields %}
{{ hidden }}
{% endfor %}
<tr>
<td>
{{ priority.priority.errors.as_ul }}
{% for value, name in priority.priority.field.choices %}
{% if value == priority.priority.value %}
<h4>{{ name }}</h4>
{% endif %}
{% endfor %}
{{ priority.priority.as_hidden }}
</td>
<td>
{{ priority.score.errors.as_ul }}
{{ priority.score }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Update Project</button>
</div>
</form>
Also since you have multiple formsets you should provide a prefix to them to provide name clashing (See Using more than one formset in a view):
if self.request.POST:
context['adoptedreviews'] = ReviewChildFormset(self.request.POST, instance=self.object, prefix='adoptedreviews_form')
context['estimatedbudget'] = EstimatedBudgetChildFormset(self.request.POST, initial=itemNames, instance=self.object, prefix='estimatedbudget_form')
context['futureexpenditure'] = FutureExpenditureFormset(self.request.POST, instance=self.object, prefix='futureexpenditure_form')
context['previousexpenditure'] = PreviousExpenditureFormset(self.request.POST, instance=self.object, prefix='previousexpenditure_form')
context['priorities'] = PriorityChildFormset(self.request.POST, initial=initial, instance=self.object, prefix='priorities_form')
else:
context['adoptedreviews'] = ReviewChildFormset(instance=self.object, prefix='adoptedreviews_form')
context['estimatedbudget'] = EstimatedBudgetChildFormset(initial=itemNames, instance=self.object, prefix='estimatedbudget_form')
context['futureexpenditure'] = FutureExpenditureFormset(instance=self.object, prefix='futureexpenditure_form')
context['previousexpenditure'] = PreviousExpenditureFormset(instance=self.object, prefix='previousexpenditure_form')
context['priorities'] = PriorityChildFormset(initial=initial, instance=self.object, prefix='priorities_form')
Note: You seem to have weird HTML (multiple tbody elements in a table??), and also you might want to reconsider having so many
formsets in a page, this can be considered bad for UX purposes (This
can be really confusing for the user, not to mention the developer
too). One page should ideally serve one purpose to the user.

NoReverseMatch at /kitty_view Reverse for 'kitty' with arguments '(5,)' not found. Same url i have tried for another app and that is working [duplicate]

This question already has an answer here:
NoReverseMatch at /kitty_view Reverse for 'kitty' with arguments '(5,)' not found. 1 pattern(s) tried: ['kitty$']
(1 answer)
Closed 3 years ago.
// While rendering this kitty_view I am getting this error. Exactly the same thing I have copied from another app that is working properly. Kindly help. Exactly same thing is working for some other app.
view.py
------------------
def kitty_view(request):
kitty_list = kitty.objects.all().order_by('-cretime')
code1 = str(request.GET.get('Code'))
name1 = str(request.GET.get('nam'))
status1 = str(request.GET.get('stat'))
if (name1 is not None and name1 != ''):
kitty_list = kitty_list.filter(name=name1)
if (code1 is not None and code1 != ''):
kitty_list = kitty_list.filter(code='K00001')
if (status1 is not None and status1 != ''):
kitty_list = kitty_list.filter(status = 'A')
ctx = {'kitty': kitty_list}
return render(request, 'kitty/kitty_view.html', ctx)
Url.py
-----
urlpatterns = [
path('',views.index,name='index'),
path('kitty_view',views.kitty_view,name='kitty_view')
]
template
---------
<form class="form-signin" action="{% url 'kitty_view' %}" method="get">
{% csrf_token %}
<div class="form-row">
<div class="mb-3">
<select class="custom-select center-block" name="code" id="code">
<option value="">Choose Kitty...</option>
<!-- <option>{{ kitty1.code }}</option>
{% for i in kitty1 %}
<option value="{{ i.code }}"> {{ i.code|add:' - '|add:i.name }} </option>
{% endfor %} -->
<option>K00004</option>
<option>K00005</option>
</select>
</div>
<div class="mb-3">
<input type="text" name="nam" id="nam" class="form-control-sm center-block" placeholder="Name" autofocus>
</div>
<div class="mb-3">
<select class="custom-select center-block" name="stat" id="stat" placeholder="Status">
<option value="">Choose Status...</option>
<option>A</option>
<option>I</option>
</select>
</div>
<div class="mb-3">
<!-- Search -->
<button type="submit" class=" btn btn-info " role="button">Search</button>
</div>
</div>
</form>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Kitty Code</th>
<th scope="col">Name</th>
<th scope="col">Type</th>
<th scope="col">Start Date</th>
<th scope="col">Total Months</th>
<th scope="col">End Date</th>
<th scope="col">Total Members</th>
<th scope="col">Amount</th>
<th scope="col">Installment</th>
<th scope="col">Status</th>
<th scope="col">Details</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>
{% if kitty %}
<h1>Biswajit1</h1>
{% for i in kitty %}
<h1>Biswajit</h1>
<tbody>
<tr>
<td>{{ i.id }} </td>
<td>{{ i.code }} </td>
<td>{{ i.name }} </td>
<td>{{ i.type }} </td>
<td>{{ i.startdate }} </td>
<td>{{ i.noofmonths }} </td>
<td>{{ i.enddate }} </td>
<td>{{ i.totalmembers }} </td>
<td>{{ i.totalamount }} </td>
<td>{{ i.noofinstallments }} </td>
<td>{% if i.status == 'A' %}
{{ 'Active' }}
{% else %}
{{ 'Inactive' }}
{% endif %}
</td>
</tr>
</tbody>
{% endfor %}
{% endif %}
</table>
{% endblock %}

How to persist data found in tables within a django template, in postgresql

I am scraping several sites and I show the data obtained in 6 tables within a django template.
My intention is to persist the data of the tables in postgresql, but I can not realize how to perform that task.
In principle I am trying to save the data from the second table.
For this I have created the models that I show below, as well as a view that is called: registroDivisaArgentina ().
The template is called quotes.html and within it, there are 6 tables.
I have tried to work with a class called: RegisterArgentineValues () within a forms.py file
models.py
class DivisasArgentina(models.Model):
class Meta:
ordering = ['CodigoDA']
CodigoDA = models.CharField(max_length=50, primary_key = True)
Texto_para_Reporte = models.CharField(max_length=70)
def __str__(self):
return '{}'.format(self.Texto_para_Reporte)
class ValoresDivisasArgentina(models.Model):
class Meta:
ordering = ['Dia']
DivisasArgentina = models.ForeignKey(DivisasArgentina, on_delete=models.PROTECT)
Dia = models.DateField(default=date.today)
Hora = models.DateTimeField(default=timezone.now)
Compra = models.FloatField()
Venta = models.FloatField()
Variacion_dia_anterior = models.FloatField()
ClaveComparacion = models.CharField(max_length=1)
def __str__(self):
return '{} - {} - {}'.format(self.DivisasArgentina, self.Dia, self.ClaveComparacion)
cotizaciones.html
{% extends 'base.html' %}
{% block contenido %}
<form method="POST" class="post-form">{% csrf_token %}
<div class="container">
<table class="table table-striped table-bordered" id="tab1">
<thead>
<tr>
<th>Divisas en el Mundo</th>
<th>Valor</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_mun%}
<tr>
{% for key,value in element.items %}
<td> {{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tbody>
</table>
</div>
<div class="container">
<table class="table table-striped table-bordered" id="tab2">
<thead>
<tr>
<th>Divisas en Argentina</th>
<th>Compra</th>
<th>Venta</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_arg%}
<tr>
{% for key,value in element.items %}
<td>{{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tbody>
<thead>
{{ form.as_table }}
</table>
</div>
<div class="container">
<table class="table table-striped table-bordered" id="tab3">
<thead>
<tr>
<th>Dolar Banco Nacion Argentina (Divisas)</th>
<th>Compra</th>
<th>Venta</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_exp%}
<tr>
{% for key,value in element.items %}
<td>{{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tbody>
</table>
<table class="table table-striped table-bordered" id="tab4">
<thead>
<tr>
<th colspan="4">Dolar Futuro en Argentina</th>
</tr>
<tr>
<th>Mes 1</th>
<th>Mes 2</th>
<th>Mes 3</th>
<th>Mes 4</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_dol%}
<td>
{{ element.Valores}}
</td>
{% endfor %}
</tr>
</tbody>
</table>
<table class="table table-striped table-bordered" id="tab5">
<thead>
<tr>
<th colspan="3">Indicadores Varios - Tasa Libor</th>
</tr>
<tr>
<th>Libor a 1 Mes</th>
<th>Libor a 2 Mes</th>
<th>Libor a 3 Mes</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_lib%}
<td>
{{ element.Valores }}
</td>
{% endfor %}
</tr>
</tbody>
</table>
<table class="table table-striped table-bordered" id="tab6">
<thead>
<tr>
<th>Indicadores Varios - Indice Merval y Oro</th>
<th>Valores</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_ind%}
<tr>
{% for key,value in element.items %}
<td> {{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tr>
</tbody>
</table>
</div>
<div class="container" id="saveData">
<br></br>
<button type="submit" class="btn btn-primary pull-right">Guardar Datos</button>
</div>
</form>
{% endblock %}
views.py
def mostrar_cotizaciones(request):
cotiz_arg = json.loads(j_cotizaciones_argentina)
cotiz_mun = json.loads(j_cotizaciones_mundiales)
cotiz_exp = json.loads(j_cotizacion_export)
cotiz_dol = json.loads(j_dolar_futuro)
cotiz_ind = json.loads(j_indicadores)
cotiz_lib = json.loads(j_libor)
context = {'cotiz_mun': cotiz_mun,
'cotiz_arg': cotiz_arg,
'cotiz_exp': cotiz_exp,
'cotiz_dol': cotiz_dol,
'cotiz_ind': cotiz_ind,
'cotiz_lib': cotiz_lib,
}
return render(request, 'cotizaciones.html', context)
def registrarDivisaArgentina(request):
if request.method == 'POST':
formulario = RegistrarValoresDivisasArgentinas(request.POST)
if formulario.is_valid():
formulario.save()
return HttpResponseRedirect('/listadoValores')
else:
formulario = RegistrarValoresDivisasArgentinas()
formulario.setup('Registrar', css_class="btn btn-success")
return render(request, 'cotizaciones.html', {'formulario':formulario})
forms.py
from django import fla
from django.forms import ModelForm
from django import forms
from fla.models import *
class RegistrarValoresDivisasArgentinas(forms.ModelForm):
class Meta:
model = ValoresDivisasArgentina
fields= [Compra, Venta]
I have done some tests, but none has given a favorable result. Someone can tell me how to process the data (in the views and forms) that are in the tables, to be able to store them in my postgres tables ?
I do this kind of task very often, and I've found out that the combination of ScraPy with scrapy-djangoitem is a very good combo to use here.
Good luck!

Django Datatables view

Im trying to convert my tables in my django app to datatables using django-tables2.
Im my campaigns.py view I have:
class CampaignListView(FacebookAdInit):
""" CampaignListView for viewing all the campaigns"""
def get(self, request, *args, **kwargs):
ad_account = self.get_ad_account(kwargs.get('ad_account_id'))
campaigns = self.get_campaigns(ad_account.get('id')) \
if ad_account else None
context = {'campaigns': campaigns, 'ad_account': ad_account}
return render(request, 'app/campaigns/index.html', context)
Im my campaigns/index.html I have:
{% extends "app/empty_page.html" %}
{% load render_table from django_tables2 %}
{% block content %}
{% if ad_account %}
{% render_table context %}
{% endif %}
{% endblock %}
However this gives me the error: Expected table or queryset, not 'str'.
ANy help will be greately appreciated.
Right now I generate the table using this piece of code:
<table class="table table-bordered table-striped" id="campaigns">
<thead>
<tr>
<th> #</th>
<th> Campaign Name</th>
<th> Campaign Objective</th>
<th> Campaign Effective Status</th>
</tr>
</thead>
<tbody>
{% for campaign in campaigns %}
<tr>
<td> {{ forloop.counter }} </td>
<td>
<a href="/ad_accounts/{{ ad_account.id }}/campaigns/{{ campaign.id }}/ad_sets">
{{ campaign.name }} </a>
</td>
<td> {{ campaign.objective }}</td>
<td> {{ campaign.effective_status }} </td>
</tr>
{% endfor %}
</tbody>
</table>
You should pass a Table instance or queryset to the render_table tag.
{% render_table campaigns %}

How to get object name by queryset in django

Is there any attribute or method to get objects'name by queryset in django
I have some code like this
# in views.py
product = []
product.append(Pc.objects.filter(user__name=pk)) ## user is a foreignkey
product.append(Monitor.objects.filter(user__name=pk))
arr = { 'type': 1,
'product': product,
'name': name,
}
return render_to_response('list.html', arr)
In template list.html
......
<tbody>
{% for pr in product %}
<tr style="text-align:center" class="form-inline">
<td>
{{ name }}
</td>
{% for p in pr %}
<td>
{{ p.number }}
</td>
<td>
{{ p.product }}
</td>
<td>
{{ p.comment }}
</td>
<td>
<a href="/update/objects/{{ p.id }}/" class="btn btn-success btn-sm" >edit</a>
<a href="/delete/objects/{{ p.id }}/" onclick="return confirm('Are you sure to delete?')" class="btn btn-danger btn-sm" >delete</a>
</td>
{% endfor %}
{% endfor %}
</tr>
</tbody>
How should I get the "objects" like Pc or Monitor in list.html?
Instead of trying to get the type and then displaying the class name in the template why don't you just add a static attribute to the classes?
class Pc(models.Model):
product_display_name = 'PC'
class Monitor(models.Model):
product_display_name = 'Monitor'
Then in the template
{% for p in pr %}
<td>
{{ p.product_display_name }}
</td>
<td>
{{ p.number }}
</td>
{% endfor %}
If you would really like to get the name from the type then you can use the following
type(instance).__name__