Categories
Python Answers

How to look up a dictionary value with a variable with a Python Django template?

To look up a dictionary value with a variable with a Python Django template, we can add a custom template filter.

For instance, we write

from django.template.defaulttags import register

##...

@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

to use the register_filter decorator to add the get_item template filter.

In it, we call dictionary.get with the key to return the value of the given key.

Then we use it by using

{{ mydict|get_item:item.NAME }}

in our template

We use get_item with item.NAME we the key and mydict as the dictionary value.

Categories
Python Answers

How to upload a file in Python Django?

To upload a file in Python Django, we can get the upload files from request.FILES.

For instance, we write

for key, file in request.FILES.items():
    path = file.name
    dest = open(path, 'w')
    if file.multiple_chunks:
        for c in file.chunks():
            dest.write(c)
    else:
        dest.write(file.read())
    dest.close()

to loop through the request.FILES dictionary in our view function.

And then we can write the files into disk with write.

We can add a simple upload form with

<form action="/upload_file/" method="post" enctype="multipart/form-data">
  {% csrf_token %}
  <label for="file">Filename:</label>
  <input type="file" name="file" id="file" />
  <br />
  <input type="submit" name="submit" value="Submit" />
</form>

which has a file input.

The action attribute of the form is set to the URL of the file upload view.

Categories
Python Answers

How to extend the User model with custom fields in Python Django?

To extend the User model with custom fields in Python Django, we can extend the AbstractBaseUser class.

For instance, we write

from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)

class MyUser(AbstractBaseUser):
    email = models.EmailField(
                        verbose_name='email address',
                        max_length=255,
                        unique=True,
                    )
    date_of_birth = models.DateField()
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['date_of_birth']

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __unicode__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    @property
    def is_staff(self):
        return self.is_admin

to create the MyUser model class which is a child of the AbstractBaseUser model class.

In it, we add new fields and methods which we use as computed properties that combines values from other class fields.

We have the email, date_of_birth, is_active, and is_admin` fields.

And the class methods are computed properties.

Categories
Python Answers

How to combine two or more querysets in a Python Django view?

To combine two or more querysets in a Python Django view, we can use the itertools chain method.

For instance, we write

from itertools import chain
result_list = list(chain(page_list, article_list, post_list))

to call chain with the page_list, article_list, and post_list querysets.

Then we convert the combined querysets into a list with list.

Categories
Python Answers

How to split cell into multiple rows in a Python Pandas dataframe?

Sometimes, we want to split cell into multiple rows in a Python Pandas dataframe.

In this article, we’ll look at how to split cell into multiple rows in a Python Pandas dataframe.

How to split cell into multiple rows in a Python Pandas dataframe?

To split cell into multiple rows in a Python Pandas dataframe, we can use the apply method.

For instance, we write

df.set_index(['order_id', 'order_date'])
   .apply(lambda x: x.str.split(',').explode())
   .reset_index()

to call apply with a lambda function that calls str.split to split the x string value.

And then we call explode to fill new rows with the split values.

Finally, we call `reset_index to reset the index numbers after filling the rows with the split values.

Conclusion

To split cell into multiple rows in a Python Pandas dataframe, we can use the apply method.