How to get object name by queryset in django - 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__

Related

Django inline formset not valid on update

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)

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.

how to pass the selected check box id of a input tag to views in django and bulk update the selected rows in table

** 1.how to pass the selected check box id of a input tag(which is in for loop, so the name and value of input tag are dynamic ) to views in django and bulk update the selected rows of table in django**
<div class="jumbotron">
<form method="post" action="">
{% csrf_token %}
{{form|crispy}}
<input class = "btn btn-primary" type="submit" value="Search">
</form>
<h3 > Model values </h3>
<ul>
<table class="table" id="tab1">
<thead>
{% if teams %}
<tr>
<th>Select</th>
<th>#</th>
<th><b>Logo</b> </th>
<th><b> Team </b></th>
</tr>
</thead>
<tbody>
{% for value in models %}
<tr>
<td><input name="lol" type = "checkbox" value = "{{value.id}}"/> </td>
<td> {{forloop.counter}}</td>
<td> <img class="w3-display-topmiddle w3-container" src="{{ value.logUri.url }}" alt="alt txt" height="910" width="910"></td>
<td> {{ value.name }} </td>
</tr>
{% endfor %}
</tbody>
</table>
**realized that since i am not keeping input tag in form tag the input tag's name values is not captured by request.POST(now changes are dome in html as below ),later in django views i removed the unnecessary keysvalues using dict.pop() and created a list containing on primary keys
in django orm (model.filter(id__in= lst_of_id_captured).update(field='somevalue') **
<form method="post" action="">
{% csrf_token %}
{{form|crispy}}
<h3 > Model values </h3>
<ul>
<table class="table" id="tab1">
<thead>
{% if teams %}
<tr>
<th>Select</th>
<th>#</th>
<th><b>Logo</b> </th>
<th><b> Team </b></th>
</tr>
</thead>
<tbody>
{% for value in models %}
<tr>
<td><input name="lol" type = "checkbox" value = "{{value.id}}"/> </td>
<td> {{forloop.counter}}</td>
<td> <img class="w3-display-topmiddle w3-container" src="{{ value.logUri.url }}" alt="alt txt" height="910" width="910"></td>
<td> {{ value.name }} </td>
</tr>
{% endfor %}
</tbody>
</table>
<input class = "btn btn-primary" type="submit" value="Search">
</form>

Django Template loop with variable

I am having issue with django html variable so I made the below code which is working .
{%for field in instance %}
<tr>
<td width="250">
{{ field.Item }}
</td>
<td>
<input type="text" value={{ field.P_640 }} >
</td>
{% endfor %}
But at the view section I have variables and sometimes I am pushing filter value. P_640 and sometimes P_630 .How can I make my template to look to the colomn 1 instead of looking the field name like {{ field.P_640 }} , because it's not working when I push P_630. ?
This is how you would do it:
{% for field in instance %}
<tr>
<td width="250">
{{ field.Item }}
</td>
<td>
<input type="text" value="
{% if field.P_640 }}
{{ field.P_640 }}
{% elif field.P_630 %}
{{ field.P_630 }}
{% endif %}
">
</td>
</tr>
{% endfor %}
Check for every value that could exist and then output it.
If there are multiple values, replace {% elif %} with {% endif %} {% if %};

Displaying Unescaped in Django Template

I have a form with a title and body but for certain cases the title should be autofilled to a value from the page:
To solve this I used a hidden input type:
<form action="" method="POST"> {% csrf_token %}
<table>
<tr>
<td>
<b>Title: </b>
</td>
{% url 'forum:new_topic' forum.pk as the_url %}
{% ifequal request.path the_url %}
<td>
{{ modelform.title}}
</td>
{% else %}
<td>
{% autoescape off %}
<input type="hidden" value="{{ modelform.title}}" >
{% endautoescape %}
Re:{{ thread.title }}
</td>
{% endifequal %}
</tr>
<tr>
<td>
<b>Body: </b>
</td>
<td>
{{ modelform.body}}
</td>
</tr>
</table>
<input type="submit" value="Submit" />
</form>
However the way it displays on the page is "> Re: .... and is for some reason not escaping the ending quote and >. I tried single quotes but that prevents submission.
Not sure what direction I should go in.