DEV Community

loading...

Django oneliners Part-1

Ajeeb.K.P
Muslim, Husband, Programmer, Indian/Kerala. Speaks English, Malayalam. Always curious about technology, computing etc.
・2 min read

Introduction

Writing one liners are cool. Let's try some.

Hello world

python -c "print('hello world')"

Another example is as follows,

python -c "from datetime import datetime; print(datetime.now())"

# Now lets take looping example,

python -c "for i in range(10): print(f'{i} x {7} = {(i+1)*7}')"

# Now let's write this to a file

python -c "with open('myfile.txt','w') as myfile: myfile.write('Hello world')"

myfile.txt is created in same folder you run above command.

Let's run some django code. Assuming project was created using

mkdir myproject && cd myproject && django-admin startproject config .

Also, you did the migration
python manage.py migrate

And your running below commands from root of django project (ie same as folder of manage.py ).

python -c "import os, sys; PWD = os.getenv('PWD'); os.chdir(PWD); sys.path.insert(0, os.getenv('PWD')); os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings'); import django; django.setup(); from django.utils import timezone; print(timezone.now())"

Bonus, let's make above thing simple, with a little bit of bash scripting.
In your ~/.bashrc or may be in ~/.bash_aliases


function djc()
{
python -c "import os, sys; PWD = os.getenv('PWD'); os.chdir(PWD); sys.path.insert(0, os.getenv('PWD')); os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings'); import django; django.setup(); $1"
}

Now open a new termianl or run

source ~/.bashrc

or

source ~/.bash_aliases

..

Now try following from the root of a django project.

djc "from django.utils import timezone; print(timezone.now())"

Assuming you have devtools installed (pip install devtools==0.5.1 to install)

djc "from django.utils import timezone; from devtools import pprint; pprint(timezone.now())"

List all django users

djc "from django.contrib.auth import get_user_model; User=get_user_model(); a=User.objects.create(username='a'); a.set_password('a'); a.is_superuser=True; a.is_staff=True; a.save()"

djc "from django.contrib.auth import get_user_model; User=get_user_model(); User.objects.all()"

djc "from django.contrib.auth import get_user_model; User=get_user_model(); print(User.objects.values_list())"

Tested on Debian 11, Python 3.6

Conclusion

One-liners are awesome. By using these one-liners. You can save some time.

Discussion (0)