Python

5 things you might not know in Django

5 things you might not know in Django: When can you claim that you have understood a certain language or a framework? Just when you are comfortable using it? Noooo. Okay, this might not be true for every piece of tech. But, I am talking about those bulky and overly featured frameworks. Yes, yes I know that you know, Django and Rails.

Django is a high-level Python web framework with lots of features. While exploring Django, we often become unaware of how some things work and might miss out on some cool features it offers. Sometimes it’s easy to skip some basics things like these, too.

I also have a lot to explore but I am sharing some basic things I got to know.

I assume, if you have worked with Django a bit, you must be easily able to understand this blog. Let’s get started…


5 things you might not know in Django

Model.objects.all()

“We all have used this query. Whats new?”

Ever wondered how “objects” came there? Actually, there is an “objects” property, which denotes to a Manager class where all the DB related queries are.

So can we write our own managers? If so then how?


# First define a Manager subclass
class AwebisamManager  (models.Manager) :
    def get_queryset (self) :
        return super().get_queryset().filter(author="Awebisam")

class Blog(models.Model) :
    title = models.CharField(max_length=70)
    author = models.CharField(max_length=60)
    body = models.TextField()

    objects = models.Manager() # Default Manager
    awebisam_objects = AwebisamManager() # This is how you hook

 
Advertisement

Here we have denoted that “objects” property as the default manager and awebisam_objects as AwebisamManager.

So what does this changes??

  • When we do Blog.awebisam_objects.all(), it will only return the blogs written by Awebisam. (as filtered in the get_queryset method.)

Filter list in admin panel

So there is a blog project on very low budget and you need to provide the default admin interface to all the writers. Woops!! Giving access to all blogs to everyone?? Doesn’t seem safe. So how are we gonna filter out the blogs shown inside the admin panel? Let’s see how…


@admin.register(Blog)
class BlogAdmin(admin.ModelAdmin):

    class Meta:
        model = Blog
        fields = '__all__'

    # Override get_queryset method in ModelAdmin class
    def get_queryset(self, request):
        queryset = super().get_queryset(request)  # Call the main get_queryset

        if not request.user.is_superuser:  # Filter applies only to non su
            # So only show the blogs written by the user
            queryset = queryset.filter(author=request.user)

        return queryset

So what we did here is override the original get_queryset method and filtered the blogs to show only the ones created by the user. Cool Huh?


Attaching file in email sent via Django

Hey we all might have sent mail via Django using “send_mail()“. But have you wondered if we can attach a file with the mail? As a matter of fact, we can.

Lemme talk this straight, send_mail() is derived from EmailMessage class. So we can create our own instance of EmailMessage and attach files.

#create a EmailMessage instance with (subject, message, from, to)
# we can also provide other args and kwargs
email = EmailMessage(
        'Your blog has been posted',
        f'''
        
        Hello {blog.author.first_name},
        Your blog {blog.title} has been successfully posted.

        ''',
        blog@somesite.com,
        to = [blog.author.email,],
    )
email.attach_file(blog.image)
email.send(fail_silently=False)

Parent level filter

So this must be something you already knew. If not then you will, now. 😉

We know that python is an underscore loving language. But did you know that many things in Django could be made easy with proper use of underscore and dunders.


# instead of :
special_user = User.objects.get( special=True)

special_blogs = Blog. objects.filter( user=special_user )
# We can easily do:
special_blogs = Blog.objects.filter(author__special=True)
# here __ is getting tnto author and finding the "special" property.

We are getting the required query-set by using kwarg level filters. Find out more from the docs.


Timezone

We all have seen this info message in the time field in Django Admin:
“Server time 5hr 45min behind user time.” Let’s solve.

I guess that you already knew. But if you didn’t, you can change the timezone from settings.py to TIME_ZONE = 'Asia/Kathmandu' or any other specific timezone you need. Get into this article to find more timezone codes.


So these were few things that you might not have known in Django. Hope these django tips and tricks will help you to better survive in Django development world.

If you have any queries and questions regarding Django or any tech, you can post in webmatrices forum.

Best wishes for your future endeavor. Contact me from here.

Keep Pythoning, Keep Exploring

Peace Out

4.3 8 votes
Article Rating
Subscribe
Notify of
guest
6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Sandy Sharma

Extremely awesome article! Can you please write on Vue vs React Js brother. Please…

Saugat Rajbhandari

Good.

Bishwas Bhandari

What part do you liked the most?

Dr. Golzalwiz Gamte

I would be great if we got a beginner friendly tutorial on how to build an ecommerce website with python and django?

6
0
Would love your thoughts, please comment.x
()
x