Categories
Python Answers

How to create Python script for Django app to access models without using manage.py shell?

To create Python script for Django app to access models without using , manage.py shell, we can import the model after calling os.environ.setdefault.

For instance, we write

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings")

from your_project_name.models import Location

if __name__ == '__main__':    
    l = Location()
    l.name = 'Berlin'
    l.save()

    locations = Location.objects.all()
    print locations

    berlin = Location.objects.filter(name='Berlin')
    print berlin
    berlin.delete()

to add

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings")

to set the environment to the Django environment.

Then we can import the Location model with

from your_project_name.models import Location

Then we can do what we want with the Location model in the if __name__ == '__main__' block.

Categories
Python Answers

How to get Python Django Admin to delete files when removing an object from the database/model?

To get Python Django Admin to delete files when I remove an object from the database/model, we can use the delete method.

For instance, we write

class MyModel(models.Model):
    file = models.FileField()
    #...

from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver

@receiver(pre_delete, sender=MyModel)
def mymodel_delete(sender, instance, **kwargs):
    instance.file.delete(False)

to add the mymodel_delete function and we apply the receiver decorator on it.

We call receiver with pre_delete to run mymodel_delete before deleting the model entry.

In mymodel_delete, we call instance.file.delete with False to delete the file without saving to the model.

Categories
Python Answers

How to give a Python Django app a verbose name for use throughout the admin?

To give a Python Django app a verbose name for use throughout the admin, we can set the verbose_name field in our config.

For instance, we write

from django.apps import AppConfig

class YourAppConfig(AppConfig):
    name = 'yourapp'
    verbose_name = 'Fancy Title'

in apps.py in our Django project to create the YourAppConfig class.

In it, we set the verbose_name field to the verbose name.

And then in our app’s init.py, we add

default_app_config = 'yourapp.apps.YourAppConfig'

to use the config.

Categories
Python Answers

How to pass Python Data to JavaScript via Django Python?

To pass Python Data to JavaScript via Django Python, we can call render_template_to_response with the data we want to pass to the template in a dict as the 2nd argument.

For instance, we write

from django.utils import simplejson


def view(request):
    js_data = simplejson.dumps(my_dict)
    # ...
    render_template_to_response("my_template.html", {"my_data": js_data})

to call render_template_to_response with the template file name and a dict with the data we pass to the template.

Then in our template, we write

<script type="text/javascript">
    data_from_django = {{ my_data }};
    widget.init(data_from_django);
</script>

to interpolate the my_data value in the template by putting my_data in curly braces.

Categories
Python Answers

How to do count and group by with Python Django?

Sometimes, we want to do count and group by with Python Django.

In this article, we’ll look at how to do count and group by with Python Django.

How to do count and group by with Python Django?

To do count and group by with Python Django, we can use values to do group by and Count to add the count.

For instance, we write

from django.db.models import Count
theanswer = Item.objects.values('category').annotate(Count('category'))

to call values to do a group by with the category field.

And then we have Count('category') to count all the grouped items in all the groups.

Conclusion

To do count and group by with Python Django, we can use values to do group by and Count to add the count.