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.
Related
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)
I am trying to create a simple pagination through a query of filtered instances of Need model.
The problem is that pagination doesn`t work at all, and I guess this is because of extra content.
Here is my current view, which shows pagination on front-end as an empty div:
class CategoryNeeds(ListView):
model = Need
template_name = "volunteering/category_needs.html"
paginate_by = 1
context_object_name = "needs"
def get_queryset(self):
return Need.objects.filter(category__name=self.kwargs["name"].capitalize())
def get(self, request, *args, **kwargs):
self.object_list = self.get_queryset()
category = Category.objects.get(name=kwargs["name"].capitalize())
self.extra_context = {
"category": category,
"needs": self.object_list
}
return self.render_to_response(self.extra_context)
And here is the template:
{% extends "index/index.html" %}
{% block content %}
<section class="contact-section bg-black">
<div class="container px-4 px-lg-5">
<div class="row gx-4 gx-lg-5">
<div class="col-md-4 mb-3 mb-md-0">
<div class="card-body text-center">
<h1>{{ category.name }}</h1>
<hr style="size: A5">
</div>
</div>
</div>
</div>
</section>
<section class="about-section text-center" id="about">
<div class="container px-4 px-lg-5">
<h2>Needs:</h2>
<table class="table table-dark table-striped">
<thead>
<tr>
<th scope="col">Photo</th>
<th scope="col">Title</th>
<th scope="col">Description</th>
<th scope="col">Price</th>
<th scope="col">Donation</th>
<th scope="col">City</th>
{% if user.pk == user_page.pk %}
<th scope="col">Update</th>
<th scope="col">Delete</th>
{% endif %}
</tr>
</thead>
<tbody>
{% for need in needs %}
<tr data-href="{% url "volunteering:need" need.pk %}">
<td>{% if need.photo %}<img src="{{ need.photo.url }}">{% endif %}</td>
<td>{{ need.title }}</td>
<td>{{ need.description|truncatechars:10 }}</td>
<td>{{ need.price }}</td>
<td>{{ need.donation }}</td>
<td>{{ need.city }}</td>
{% if user.pk == user_page.pk %}
<td>Update</td>
<td>Delete</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div>
{% if page_obj.has_previous %}
« Previous page
{% if page_obj.number > 3 %}
1
{% if page_obj.number > 4 %}
<span>...</span>
{% endif %}
{% endif %}
{% endif %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
{{ num }}
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
{{ num }}
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
{% if page_obj.number < page_obj.paginator.num_pages|add:'-3' %}
<span>...</span>
{{ page_obj.paginator.num_pages }}
{% elif page_obj.number < page_obj.paginator.num_pages|add:'-2' %}
{{ page_obj.paginator.num_pages }}
{% endif %}
Next Page »
{% endif %}
</div>
</section>
{% endblock %}
The reason why I think the problem lies in extra content is because this view works perfectly with pagination:
class AllNeeds(ListView):
model = Need
context_object_name = "needs"
paginate_by = 3
Could someone explain, why doesn`t my pagination work, please?
Would be very grateful for all your responce!
Yep, it seems that you are overiding normal django flow which adds context, try this:
class CategoryNeeds(ListView):
model = Need
template_name = "volunteering/category_needs.html"
paginate_by = 1
def get_queryset(self):
return Need.objects.filter(category__name=self.kwargs["name"].capitalize())
def get(self, request, *args, **kwargs):
self.object_list = self.get_queryset()
category = Category.objects.get(name=kwargs["name"].capitalize())
context = self.get_context_data()
context['category'] = category
return self.render_to_response(context)
I am trying to implement a form where candidates can be selected for approval processing. I want to display a list of candidates, so their data can be viewed during selection.
models.py
class SubmissionApproval(models.Model):
candidate=models.ForeignKey(Candidate,on_delete=models.CASCADE)
clientProcess=models.ForeignKey(ClientProcessDetails,verbose_name="Client
Process",help_text="Process",on_delete=models.PROTECT)
dateSubmitted=models.DateTimeField(auto_now_add=True)
comments=models.CharField("Comments",max_length=200,blank=True,null=True)
class Meta:
verbose_name="First Stage Approval"
unique_together=(('candidate','clientProcess'),)
def __str__(self):
return self.candidate.name
views.py
def submissionApprovalList(request):
object_list=Candidate.objects.all()
if request.method=="POST":
fm=SubmissionApprovalFormList(request.POST)
print("Reached Post")
if fm.is_valid():
print("Printing Candidates Start")
for item in fm.cleaned_data['candidates']:
print(item)
print("Printing candidates End")
else:
fm=SubmissionApprovalFormList()
return render(request,'itrecruitment/firstStageSubmissionList.html',{'form':fm,'object_list':object_list })
forms.py
class SubmissionApprovalFormList(forms.Form):
candidates=forms.ModelMultipleChoiceField(
queryset=Candidate.objects.all(), widget=forms.CheckboxSelectMultiple
)
template
{% extends "seekgeek/base.html" %}
{% block content %}
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<h3 class="box-title">Select Candidates for First Stage Submission</h3>
<button type="button" class="btn btn-primary pull-right">Add Candidate </button>
</div>
<!-- /. box-header -->
<div class="box-body table-responsive">
<!-- form details -->
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
{% bootstrap_messages %}
<form method="post" enctype="multipart/form-data" >
{% csrf_token %}
<table class="table table-bordered table-hover datatable2">
<thead>
<tr>
<td><b>Select</b></td>
<td><b>Candidate No</b></td>
<td><b>Candidate Name</b></td>
<td><b>Current CTC (LPA)</b></td>
<td><b>Expected CTC (LPA)</b></td>
<td><b>Experience in Yrs</b></td>
<td><b>Recruiter</b></td>
<td><b>Latest Status</b></td>
<td><b>Languages</b></td>
<td><b>Updated</b></td>
</tr>
</thead>
<!-- ./ table head -->
<tbody>
{% for obj in object_list %}
<tr>
<!--Select field for Form -->
<td> {{ form.candidates.0 }} </td>
<!--Select field for Form -->
<td>{{ obj.id }}</td>
<td>{{ obj.name }}</td>
<td>{{ obj.currentCTC }}</td>
<td>{{ obj.expectedCTC }}</td>
<td>{{ obj.experience }}</td>
<td>{{ obj.recruiter }}</td>
<td>{% if obj.latestRecStatus %}
<p><a class='text-green' href="{{ obj.latestRecStatus.get_absolute_url }}">{{ obj.latestRecStatus }}</a></p>
<p><a class='text-yellow' href="{% url 'clients:process-detail' obj.latestRecStatus.clientProcess.id %}"> {{ obj.latestRecStatus.clientProcess }} </a></p>
{% else %}
<p>No Status</p>
{% endif %}
</td>
<td>
{% for item in obj.programmingLanguages.all %}
<p>{{ item }}</p>
{% endfor %}
</td>
<td>{{ obj.updated }}</td>
</tr>
{% endfor %}
</tbody>
<!-- /. table body -->
</table>
<!-- /. table -->
{% buttons %}
<button type="submit" class="btn btn-primary">
Submit
</button>
{% endbuttons %}
</div>
<!-- /. box body -->
</div>
<!-- /. box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
{% endblock %}
What is the correct way of doing this. intention is similar to change list form in django admin
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 %}
I am using a Django formset for this model:
class Book(models.Model):
book_id=models.AutoField(primary_key=True,unique=True)
book_name=models.CharField(max_length=30)
publisher_name=models.CharField(max_length=40)
author=models.ForeignKey(Author)
The formset is defined thus:
BookFormset = inlineformset_factory(Author, Book,
fields=('book_id','book_name', 'publisher_name'), extra=1,
can_delete=False)
The template is:
{{ formset.non_form_errors.as_ul }}
<table id="formset" class="form">
{% for form in formset.forms %}
{% if forloop.first %}
<thead><tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}
{% endfor %}
</tr></thead>
{% endif %}
<tr class="{% cycle row1,row2 %}">
{% 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>
{% endfor %}
</table>
The fields are displayed column-wise, but I would like them to be displayed row-wise.
The above code produces output like this:
Book name Publisher name
book_field Publisher_field
I would like the output to look like this:
Book name book_field
Publisher name Publisher_field
How can I do this?
In your template, you have two <tr> elements, each of which contains a loop over form.visible_fields, each iteration of which generates a single <th> or <td>.
Change this round so that you have a single loop over form.visible_fields, each iteration of which contains a single <tr> element containing a <th> and a <td>. Like this:
<table id="formset" class="form">
{% for form in formset.forms %}
{% for field in form.visible_fields %}
<tr class="{% cycle row1,row2 %}">
<th>{{ field.label|capfirst }}</th>
<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>
</tr>
{% endfor %}
{% endfor %}
</table>
The examples above seem to show a column-wise layout, which appears to be the default layout when a formset renders itself.
To make it row-wise, use something like this:
<table>
{% for form in formset.forms %}
{% if forloop.first %}
<thead>
{% for field in form.visible_fields %}
<th>{{ field.label }}</th>
{% endfor %}
</thead>
<tbody>
{% endif %}
<tr class="{% cycle row1,row2 %}">
{% for field in form.visible_fields %}
<td>
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% if forloop.last %}
</tbody>
{% endif %}
{% endfor %}
</table>