Categories
Python Answers

How to create a JSON response using Django and Python?

To create a JSON response using Django and Python, we can use the JsonResponse class.

For instance, we write

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})

to create a JsonResponse instance with a dictionary that we want to return as the response JSON body.

Categories
Python Answers

How to check if a field has changed when saving with Python Django?

To check if a field has changed when saving with Python Django, we can override the `init method of the model class to keep a copt of the original value.

For instance, we write

class Person(models.Model):

    name = models.CharField()

    __original_name = None

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__original_name = self.name

    def save(
        self,
        force_insert=False,
        force_update=False,
        *args,
        **kwargs
        ):
        if self.name != self.__original_name:
            super().save(force_insert, force_update, *args, **kwargs)
            self.__original_name = self.name

to add the __init__ method that sets the __original_name variable to self.name to keep the original name value.

And then in the if block in save, we check self.name to see if it’s different from self.__original_name to see if it’s saved with a new value.

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.