Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 26, 2023 12:28 am

10 Insanely Useful Django Tips


There are quite a few great little tricks and tips one could use on their Django projects that would speed up development and save many headaches in the long run. From basic to obscure, these tips can help any skill-level of programmer become more adept with Django and all it's glory.


Django is an excellent framework for Python. While it may not get as much ink as other popular frameworks like Rails, it is just as much a polished framework as any of the rest. It puts plenty of emphasis on the DRY principle (Don't Repeat Yourself) in clean coding by automating many of the processes in programming.


1. Use Relative Paths in the Configuration


Relative path means using the path relative to the current working directory to define files rather than hardcoding the full path. For some reason, projects tend to be moved around in location from time to time. This can be an absolute bear to deal with if you don't first plan ahead for the possibility. If you don't use relative paths, the project will break if another person is working on the same project or the application is deployed to the server. Rob Hudson has an excellent technique to ensure that your Django deployments can be moved around with ease, only having to edit a few lines of code in your settings files.



My default Django settings file has changed over time to now include settings that do not depend on the location of the project on the file system. This is great in a team environment where more than one person is working on the same project, or when deploying your project to a web server that likely has different paths to the project root directory.



The correct way to define the static directories is by following the relative path. By default, Django provides the BASE_DIR and even gives you an hint about how to define your paths.











1
# Build paths inside the project like this: BASE_DIR / 'subdir'.

2
BASE_DIR = Path(__file__).resolve().parent.parent

Here is how you would define the STATIC_ROOT and the MEDIA_ROOT directories.











1
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
2
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')


Photo by kaet44.

2. Use the {% url %} Tag


Instead of hardcoding individual links, try using the backwards compatible {% url %} tag to achieve the same result. This will give you the absolute URL, so that if, heaven forbid, your Django project moves the links will still remain in tact.


Essentially {% url %} takes a view name and its parameters and does a reverse lookup to return the queried URL. If you make changes to your urls.py file, the links won't break.


While it's not the most advanced tip, it's an excellent technique to use in your Django projects.



Photo by Dave_Apple.

3. Use select_related and prefetch_related


Unnecessary queries will always have adverse effects on database performance. Databases use foreign keys and many-to-many relationships to manage relationships between tables. select_related allows developers to fetch related objects in a foreign key relationship, while prefetch_related allows developers to fetch related objects in many to many or reverse Foreign key relationships. These two methods will allow you to reduce the number of queries done to the database. For example, suppose you have the following models:































































1
class Author(models.Model):
2
    full_name = models.CharField(max_length=100)
3

4
    def __str__(self):
5
        return self.full_name
6

7
   
8
class Course(models.Model):
9
    title = models.CharField(max_length=100)
10
    description = models.TextField()
11
    author = models.ForeignKey(Author)
12

13

14
    def __str__(self):
15
        return self.title

Lets perform queries using select_related and prefetch_related.



































1
>>> from mysite.models import Course,Author
2
>>> tutorials = Course.objects.select_related('author').all()
3
>>> tutorials
4
<QuerySet [<Course: Web development with Django>, <Course: understanding django>, <Course: python sysyems>]>
5
>>> tutorials1 = Course.objects.prefetch_related('author').all()
6
>>> tutorials1
7
<QuerySet [<Course: Web development with Django>, <Course: understanding django>, <Course: python sysyems>]>
8
>>> 

4. Use a Separate Media Server


Django allows you to serve static files in your development environment but not your production environment. Why? It's not efficient. 


Serving static files in the same server as your django application can slow things down. The best solution is to use a dedicated server such as nginx, a cloud service, or a CDN. Some of the storage cloud service solutions available are:



  • Cloudinary

  • Amazon S3

  • Google cloud storage

  • Azure file storage


These provide a faster way of serving static files, hence improving your website performance. By using a separate server to house and serve these static files, your performance won't suffer. If you didn't want to buy a server, you could use Amazon S3 to house the files relatively cheaply.



Django deliberately doesn't serve media for you, and it's designed that way to save you from yourself. If you try to serve media from the same Apache instance that's serving Django, you're going to absolutely kill performance. Apache reuses processes between each request, so once a process caches all the code and libraries for Django, those stick around in memory. If you aren't using that process to service a Django request, all the memory overhead is wasted.




Photo by winkyintheUK.

5. Use the Debugger Toolbar


Debugging tools for any language are invaluable. They speed up development by spotting errors in your code and potential pitfalls that might happen. The Django debug toolbar to help with debugging code, and it could greatly help any developer.



The toolbar itself is a piece of middleware that instantiates each panel object on request, and performs processing and rendering as the response is being written back to the browser. In this way it is essentially a set of middleware classes (the panels) grouped together to display a single toolbar. Each panel subclasses a base panel class and overrides a few methods to render the toolbar.



 

The Django debug toolbar is also used to observe slow running queries and can help with database optimization. Here is a screenshot showing the toolbar in action.

django debug toolbardjango debug toolbardjango debug toolbar

6. Use Django Unit Testing


Unit testing is a great way to ensure that your changes to the code that it works as expected and doesn't break any older code to maintain backwards compatibility. A great feature in Django is that it's incredibly easy to write unit tests. Django offers the ability to use the doctest or unittest straight out of the box.


Django's documentation offers a great tutorial and some sample code on how to set up unit tests to keep your code running smoothly and spot any nasty bugs.



Photo by Dave_Apple.

7. Use a Virtual Environment to Manage Dependencies


Unlike other programming languages, Python is not good at managing application dependencies. Virtual environments allow you to separate system dependencies from application dependencies. For example, suppose you have Python 3.9 globally installed in your operating system. In that case, a virtual environment will allow you to use different versions of Python in different projects on the same machine. Another great tip is to use the requirements.txt file to list every library or package used in your project.


Different versions of particular packages might cause things to break. If you're interested, you can read more about virtual environments.



Photo by quimpg.

8. Use Class-Based Views


Django provides class-based views which abstract the implementation of some repetitive tasks. Class-based views are reusable and make adding logic with minimal code changes easy. For example, look at the code below for submitting a form using class-based and function views.



















































































































































1
# function based view

2

3
def member_form(request):
4
    if request.method == 'POST':
5
        form = MemberForm(request.POST)
6
        if form.is_valid():
7
            member = Member( 
8
                first_name = request.POST['first_name'],
9
                last_name = request.POST['last_name'],
10
                email = request.POST['email'],
11
                address = request.POST['address'],
12
                mobile = request.POST['mobile'])
13
            member.save()
14
            return HttpResponse("Member Added")
15
 
16

17
    else: 
18
        form = MemberForm()
19

20
    return render(request, 'mysite/member_form.html', {'form': form})
21

22

23

24
# Class Based View: 

25

26
from django.views.generic import CreateView
27
from .models import Member
28

29
class SubmitFormView(CreateView):
30
    model = Member 
31
    fields = ['first_name', 'last_name', 'email', 'address', 'mobile'] 
32
    template_name = 'mysite/member_form.html' 
33

34
    def form_valid(self, form): 
35
        form.save() 
36
        return HttpResponse("Member Added")

As you can see above, the class-based view will need minimal changes if the logic changes.



Photo by Vince Huang.

9. Use Memcache


If performance is going to be an issue with your Django-powered application, you'll want to install some sort of caching. While Django offers many options for caching, the best by far is memcached.  Other types of caching available in Django include



  • database caching

  • file system caching

  • local caching

  • dummy caching



Photo by lastrandy.

10. Stop Hacking Scripts Together and Just Use Django


If you still don't fully understand Django's power, there's a logical reasoning for using Django in your next project: You save time hacking together designs with different sets of software. According to Jeff Croft , one of the co-creators of Django, 



Now, if you're used to building sites using a blogging app (WordPress, TXP, etc.) as a CMS, you're used to getting all that for free. But you're also getting a lot of things built-in that maybe you don't want (unless, of course, you're building a blog). The limitation I ran across in using a blogging app for my personal site is that I wanted it to be more than just a blog. As soon as I tried to hack a blog into a photo gallery, or a links feed, or a statistics database, a game of Sudoku, or whatever else I could think of, things started to get crufty. I also built a website in which I tried to use a discussion forums app (vBulletin) as a CMS, and that had the same results. It worked—sort of—but it wasn't extensible, was very hackish, and just generally was inelegant.


With Django, you get all of these things and none of the limitations of a blogging app.



Django allows you to expand your website into literally any direction without having to worry about hacking the design or making sure the scripts and databases are compatible. It just works.



Photo by JennyHuang.

 

This post was updated with contributions from Esther Vaati.


Original Link: https://code.tutsplus.com/tutorials/10-insanely-useful-django-tips--net-974

Share this article:    Share on Facebook
View Full Article

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code