How to put many fields of django-tables2 into one? - python

I have a django table declared as follow :
class BookTable(tables.Table):
user= tables.TemplateColumn("""{% include 'books/user.html' with user=record.created_by %}""")
books= tables.TemplateColumn(
""" {% if record.g_books.count %}
<div class="panel-body">
{% include 'books/details/detail.html' with book=record %}
</div>
{% else %}
No New Books
{% endif %}
<div>
</div>
""")
actions = tables.TemplateColumn("""{% include 'books/action.html' with book=record %}""")
I want to make changes on the order and some styles of fields and I want to render only one field that groups user, books and actions fields .
Is that possible with django-tables2 or it's a bad way to do so ?
New with django-tables2 , any advice is welcome
Thanks.

Related

How to filter in HTML using a field from model?

I want to implement a page with check boxes from university's subjects and the user can select which ones are already completed, I code a for loop that displays in the page all subjects from that course, but I want to separate the subjects by semester in a div, but in the same page, can I do this with a custom template tag or filter?
I have tried using .filter on the query, but in this case only returned one specified semester.
The regroup template tag can help.
Example template code:
{% regroup subjects by semester as semester_list %}
{% for semester, grouped_subjects in semester_list %}
<div>
{# your code for semester here #}
<div>
{% for subject in grouped_subjects %}
{# your code for subject here #}
{% endfor %}
</div>
</div>
{% endfor %}
Read more on docs
——
Edit:
regroup relies on ordering of the queryset.
Change the first line in above code to
{% regroup subjects|dictsort:'semester' by semester as semester_list %}

Django Populate Dropdown Menu With Choices From Many To Many Database

I would like to populate my dropdown menu with records from the Subject table which is a many to many choices field that is populated with subjects by adding them manually from the admin page. A course can have many subjects such as "business" and "marketing".
Code:
https://dpaste.de/825n
How would I do that with django-select2 or use a form with model select or multiple model select?
https://docs.djangoproject.com/en/2.2/ref/forms/fields/#modelchoicefield
https://docs.djangoproject.com/en/2.2/ref/forms/fields/#modelmultiplechoicefield
https://django-select2.readthedocs.io/en/latest/
Or maybe I could do it with a for loop on the template?
For loops I have tried but no luck:
https://dpaste.de/5MVi
Desired Result:
https://imgur.com/a/Iw9lk6I
Can someone please help me figure it out? I have been stuck for a while now.
here hope this helps your missing the .all() on while querying the many to many fields. you're also not going deep enough to the actual name of the many to many fields so you're trying to print the object on your loop.
example view:
def tester(request):
tes = Test.objects.get(id=1)
testlist = tes.category.all()
context = {
'test': testlist,
}
return render(request, 'core/t.html', context)
example loop:
{% for item in test %}
<p>- {{item.cat}}</p>
{% endfor %}
example model:
class cats(models.Model):
cat = models.CharField(max_length=10,)
class Test(models.Model):
name = models.CharField(max_length=10,)
category = models.ManyToManyField(cats)
nested loop example:
{% for item in item_list %}
<h2>{{ item.name }}</h2>
<ul>
{% for sub in item.subjects.all %}
<li>{{ sub.name }}</li>
{% endfor %}
</ul>
{% endfor %}
After creating your model form you can use something like this to get a dropdown
class CourseForm(forms.ModelForm):
subjects = forms.ModelMultipleChoiceField(
queryset=Subject.objects.all(),
required=True,
)
class Meta:
model = Course
fields = [......, subjects]
or you can use the other widget, widget=forms.CheckboxSelectMultiple,depending on your requirement
<form method="post" action="">
<div>
{% csrf_token %}
{{ form }}
<input type="submit" class="btn btn-primary" id="submit" value="Save">
</div>
</form>
Add a create view to create a course something like below
class CourseCreateView(CreateView):
model = Course
form_class = CourseForm
template_name = 'course_form.html'
success_url = reverse_lazy('/')

Displaying custom checkboxes with Django and ManyToManyField

I'm having trouble wiring my checkboxes together with the template to make a good user experience. I'm sending my form to the view which contains the following MyType which is described as:
models
class A(models.Model):
MyType = models.ManyToManyField(P)
forms
MyType = forms.ModelMultipleChoiceField(queryset=P.objects.all(), required=False, widget=forms.CheckboxSelectMultiple)
and the view is being sent as:
return render(request, "static/about.html", {'form': form})
and in the template, I have the following kind of structure
<li class="option table">
<div class="cell" id="center">
<div class="option-text">Option 1</div>
</div>
<div class="cell" id="right">
<div class="option-checkbox">
<div class="check"></div>
<input id="myid1" name="myname1" value="1" type="checkbox">
</div>
</div>
Now I can use answer: On a django form, how do I loop through individual options per field? to loop through, but this only gives the description. How do I recreate the actual HTML that deals with the options in the smartest way?
I've tried the shell to look at the objects, but I really don't see what I should be pulling in. i.e. in the template to recreate. What fields of each option should I pull in? or how do I get at the right info to build up my HTML such that the saving aspect of the form will work.
In a template I cannot do:
{% for field in form["MySmoking"] %}
{% endfor %}
so how could I modify the following:
{% for option in form.MyType.field.choices.queryset %}
{{ option.image }}
{{ option.title }}
{{ option.description }}
{% endfor %}
so, how would I spit out the HTML that builds the checkbox.
Thanks.

Dynamic session access in templates

I'm trying to access session keys within a loop that needs to be dynamic, I think you'll get what I'm going for by looking at my code that isn't working.
{% for q in questions %}
<div class="question_wrap">
<h2>{{ q }}</h2>
# this does not work
{% if not request.session.get(str(q.id), False) %}
<!-- show them vote options -->
{% else %}
<!-- dont show options -->
{% endif %}
</div>
{% endfor %}
The syntax of Django templates is very limiting in order to prevent people from putting too much logic inside templates and doesn't allow you to pass parameters to methods.
You can prepare a list of tuples already in the view or write a simple template tag for that. The first options is usually easier:
In the view:
questions = [(q, request.session.get(str(q.id), False)) for q in questions]
In the template:
{% for q, has_voted in questions %}
...
{% endfor %}

Question on Django: Displaying many to many fields

I seem to have a problem with Django when it comes Rendering ManyToManyField in a template. I can make it work partially, but I cannot make it work properly as I want it.
Firstly I have an invoice template which displays Invoice details from my data base
#invoice_details.html
{% extends "base.html" %}
{% block content %}
<h2>Invoice Details</h2>
<div id="horizontalnav">
Add an Invoice
Add a Work Order
Add Payment
</div>
<ul>
<div id="list">
{% for invoice in invoices_list %}
{{invoice.client}}<br/>
{{invoice.invoice_no}}<br/>
{{invoice.contract_info}}<br/>
{{invoice.date}}<br/>
{{invoice.work_orders}}<br/>
{% endfor %}
</div>
</ul>
{% endblock %}
In my database, {{invoice.work_orders}} was displayed like the following below. This is because {{invoice.work_orders}} uses a manytomanyfield
<django.db.models.fields.related.ManyRelatedManager object at 0x8a811ec>
Now I tried to change {{invoice.work_orders}} to {{invoice.work_orders.all}} and I got this.
[<Work_Order: Assurance Support Service >]
This sort of works, but I want it to display "Assurance Support Service" only. So I am wondering how I can do this change if possible.
The content of {{invoice.work_orders.all} is a list of Work_Order objects.
If you want to print them, you should iterate the list:
{% for invoice in invoice.work_orders.all %}
{{invoice}}<br />
{% endfor %}

Categories

Resources