Categories
Python Answers

How to interpolate Python Django Template Variables and JavaScript?

To interpolate Python Django Template Variables and JavaScript, we can wrap our Django variable in curly braces in our template.

For instance, we write

<script type="text/javascript"> 
  const a = "{{someDjangoVariable}}";
</script>

to interpolate the someDjangoVariable value into the JavaScript code in the template by putting it in curly braces.

Categories
Python Answers

How to make a field readonly (or disabled) so that it cannot be edited in a Python Django form?

To make a field readonly (or disabled) so that it cannot be edited in a Python Django form, we can set the readonly attribute of a field to True.

For instance, we write

class ItemForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(ItemForm, self).__init__(*args, **kwargs)
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            self.fields['sku'].widget.attrs['readonly'] = True

    def clean_sku(self):
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            return instance.sku
        else:
            return self.cleaned_data['sku']

to create the ItemForm with the

self.fields['sku'].widget.attrs['readonly'] 

dictionary value set to True to make the sku field readonly.

Categories
Python Answers

How to query as GROUP BY in Python Django?

To query as GROUP BY in Python Django, we can use the aggregation features in the Django ORM.

For instance, we write

from django.db.models import Count

result = (Members.objects
    .values('designation')
    .annotate(dcount=Count('designation'))
    .order_by()
)

to get the designation column values with values.

Then we get the count of the designation column values with Count.

And then we call order_by sort the values in ascending order.

Categories
Python Answers

How to add a form to a dynamically to a Django formset?

To add a form to a dynamically to a Django formset, we can use a for loop.

For instance, we write

<h3>My Services</h3>
{{ serviceFormset.management_form }}
{% for form in serviceFormset.forms %}
    <div class='table'>
    <table class='no_error'>
        {{ form.as_table }}
    </table>
    </div>
{% endfor %}
<input type="button" value="Add More" id="add_more">

to render the forms with form.as_table within the for loop.

We get the forms from serviceFormset.forms .

Categories
Python Answers

How to add a numeric for loop in python Django templates?

To add a numeric for loop in python Django templates, we can add it straight into the template.

For instance, we write

{% for i in '0123456789'|make_list %}
    {{ forloop.counter }}
{% endfor %}

to add a for loop in our template that loops from 0 to 9 since we have in '0123456789' as the loop expression.

We use the make_list filter to convert '0123456789' into a list.

Then we use forloop.counter to get the index.