Categories
Python Answers

How to compare floats for almost-equality in Python?

Sometimes, we want to compare floats for almost-equality in Python.

In this article, we’ll look at how to compare floats for almost-equality in Python.

How to compare floats for almost-equality in Python?

To compare floats for almost-equality in Python, we can use the math.isclose method.

For instance, we wrirew

import math
a = 5.0
b = 4.99998
is_close = math.isclose(a, b, rel_tol=1e-5)

to check if a is close b by checking if their absolute difference is 1e-5 or less.

We set the rel_tol argument to the largest absolute difference for 2 numbers to be considered close.

Conclusion

To compare floats for almost-equality in Python, we can use the math.isclose method.

Categories
Python Answers

How to find all files in a directory with extension .txt in Python?

Sometimes, we want to find all files in a directory with extension .txt in Python.

In this article, we’ll look at how to find all files in a directory with extension .txt in Python.

How to find all files in a directory with extension .txt in Python?

To find all files in a directory with extension .txt in Python, we can use the glob.glob method.

For instance, we write

import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
    print(file)

to change to the /mydir directtory with

os.chdir("/mydir")

Then we get all the files with extension .txt in the folder and print the file names by writing

for file in glob.glob("*.txt"):
    print(file)

Conclusion

To find all files in a directory with extension .txt in Python, we can use the glob.glob method.

Categories
Python Answers

How to create a dropdown in Python Django model form?

Sometimes, we want to create a dropdown in Python Django model form.

In this article, we’ll look at how to create a dropdown in Python Django model form.

How to create a dropdown in Python Django model form?

To create a dropdown in Python Django model form, we can create a char field with the choices argument set to a tuple of choices in a model class.

Then we can set the model class as the model for the form.

For instance, we write

models.py

COLOR_CHOICES = (
    ('green','GREEN'),
    ('blue', 'BLUE'),
    ('red','RED'),
    ('orange','ORANGE'),
    ('black','BLACK'),
)

class MyModel(models.Model):
  color = models.CharField(max_length=6, choices=COLOR_CHOICES, default='green')

to add the color field to the MyModel model class.

Then in forms.py, we write

class MyModelForm(ModelForm):
    class Meta:
        model = MyModel
        fields = ['color']

to create the MyModelForm that adds the color field as a field in the form.

And we set the model class to MyModel.

Then in views.py, we write

class CreateMyModelView(CreateView):
    model = MyModel
    form_class = MyModelForm
    template_name = 'myapp/template.html'
    success_url = 'myapp/success.html'

to add the CreateMyModelView view class to render MyModelForm.

In template.html, we add

<form action="" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Create" />
</form>

to render the form.

Conclusion

To create a dropdown in Python Django model form, we can create a char field with the choices argument set to a tuple of choices in a model class.

Then we can set the model class as the model for the form.

Categories
Python Answers

How to run raw SQL queries in Python Django views?

Sometimes, we want to run raw SQL queries in Python Django views.

In this article, we’ll look at how to run raw SQL queries in Python Django views.

How to run raw SQL queries in Python Django views?

To run raw SQL queries in Python Django views, we can use the cursor.execute method.

For instance, we write

from django.db import connection

cursor = connection.cursor()
cursor.execute('''SELECT count(*) FROM people_person''')
row = cursor.fetchone()

to get the cursor with connection.cursor.

Then we call cursor.execute to run a raw select query.

And then we get the first row returned with cursor.fetchone.

Conclusion

To run raw SQL queries in Python Django views, we can use the cursor.execute method.

Categories
Python Answers

How to add URL Redirect with Python Django?

Sometimes, we want to add URL Redirect with Python Django.

In this article, we’ll look at how to add URL Redirect with Python Django.

How to add URL Redirect with Python Django?

To add URL Redirect with Python Django, we can use the RedirectView.as_view method.

For instance, we write

from django.urls import re_path

re_path(r'^.*$', RedirectView.as_view(url='home', permanent=False), name='index')

to create the / route that redirects to the home URL.

We cann RedirectView.as_view with some arguments to redirect / to home.

We set the permanent to False to do a 302 redirect.

And we can set permanent to True to do a 301 redirect.

Conclusion

To add URL Redirect with Python Django, we can use the RedirectView.as_view method.