Tech C**P
14 subscribers
161 photos
9 videos
59 files
304 links
مدرس و برنامه نویس پایتون و لینوکس @alirezastack
Download Telegram
Media is too big
VIEW IN TELEGRAM
Routes implementation in `Django` and how to wire routes & views

#python #django #route #view #django_part8
One of the benefits of Django`'s `QuerySet is that you can apply filters on it, slice it and move it around your classes without actually hitting the database until you do so.

One of the ways that executes the query is using iteration:
for c in Course.objects.all():
print(c.title)
NOTE: the first time you iterate over the query, it hits the database and get the result NOT in each iteration.

In the below ways your query will be evaluated (executed):
- repr
- len
- list (e.g.: `list(Entry.objects.all())`)
- bool

#python #django #querySet #query_set #evaluation
DJANGO

Let's do a little bit more by fetching data from database and pass them to views in Django.

For now we make a change in polls/views.py in index function to get data from Question model and return it as an HTTP response object. At first let's import the model:
from .models import Question


And now in index function write the below code:
latest_question_list = Question.objects.order_by('-pub_date')[:5]
output = ', '.join([q.question_text for q in latest_question_list])
return HttpResponse(output)


The code above gets the last 5 questions and on the second line question_text fields for those que
stions are joined together by comma and finally returned as an HTTP response.

Now if you head over to http://127.0.0.1:8000/polls/ you would see the result of question texts bound together by co
mma.

#python #django #query #django_part9
Here we aim to design templates and render them to interact with Django the way it likes! We try to isolate the page's design.

Create a folder called templates in polls directory (this is the default folder name where django will look for app templates). Inside of templates create polls directory and inside of it create index.html file. So your templates are in path polls/templates/polls/index.html.

We have polls inside of templates folder to render templates in the format of loader.get_template('polls/index.html').

NOTE: if you don't create polls subdirectory inside of templates and you have templates we the same name in different apps (in the same project) you would encounter bizarre problems. DON'T DO THAT! (Django will choose the first template it finds whose name matches)

Now put the below code in polls/templates/polls/index.html:
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}


OK now do as follow in index function in polls/views.py for template rendering:
from django.http import HttpResponse
from django.template import loader
from .models import Question


def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {
'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))


Note that we have imported loader from django.template.

As you can see above, we have rendered the template with our variables (context) and passed it to http response object. We have used django.template module to render templates.

I've got the below result (next picture) what about you?

#django #loader #render #templates #django_part10
You can integrate Django with Bootstrap4 now. First install it using pip:
pip install django-bootstrap4

Add to INSTALLED_APPS in your settings.py:
'bootstrap4',

In your templates, load the bootstrap4 library and use the bootstrap_* tags:
{% load bootstrap4 %}

{# Display a form #}

<form action="/url/to/submit/" method="post" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button type="submit" class="btn btn-primary">Submit</button>
{% endbuttons %}
</form>

* Reference: http://django-bootstrap4.readthedocs.io/en/latest/

#python #django #bootstrap #bootstrap4 #template django_bootstrap4
Tech C**P
#python #django #django_part11 #views #render
In this tutorial we would go over rendering templates by using shortcuts and using dynamic urls in views. We also complete the detail function to load question details from database.

#django_part11
Make your Django application blazing fast by doing some tips:

1- Use a separate media server:
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.

So, set up all your media to be served by a different web server entirely. Ideally, this is a physically separate machine running a high- performance web server like lighttpd or tux. If you can’t afford the separate machine, at least have the media server be a separate process on the same machine.

For more information on how to separate static folder:
- https://docs.djangoproject.com/en/dev/howto/static-files/#howto-static-files


2- Use a separate database server:
If you can afford it, stick your database server on a separate machine, too. All too often Apache and PostgreSQL (or MySQL or whatever) compete for system resources in a bad way. A separate DB server — ideally one with lots of RAM and fast (10k or better) drives — will seriously improve the number of hits you can dish out.


3- Turn off KeepAlive:
I don’t totally understand how KeepAlive works, but turning it off on our Django servers increased performance by something like 50%. Of course, don’t do this if the same server is also serving media… but you’re not doing that, right?


4- Use memcached:
Although Django has support for a number of cache backends, none of them perform even half as well as memcached does. If you find yourself needing the cache, do yourself a favor and don’t even play around with the other backends; go straight for memcached.


#python #django #memcached
How to find the query associated with a queryset in Django ORM?

Sometime you want to know how a Django ORM makes our queries execute or what is the corresponding SQL of the code you are writing. This is very strightforward. Youn can get str of any queryset.query to get the sql.

You have a model called Event. For getting all records, you will write something like Event.objects.all(), then do str(queryset.query)


>>> queryset = Event.objects.all()
>>> str(queryset.query)
SELECT "events_event"."id", "events_event"."epic_id",
"events_event"."details", "events_event"."years_ago"
FROM "events_event"



Example 2:

>>> queryset = Event.objects.filter(years_ago__gt=5)
>>> str(queryset.query)
SELECT "events_event"."id", "events_event"."epic_id", "events_event"."details",
"events_event"."years_ago" FROM "events_event"
WHERE "events_event"."years_ago" > 5


#python #django #orm
In Django unittests you can use fixtures in order to create dummy data. To create fixtures you can use django dumpdata command to dump a specific data:

python3 manage.py dumpdata --indent 4 YOUR_APP.YOUR_TABLE > output_data.json


This is how you can dump data and use it as your data backend for unittests.

#django #python3 #dumpdata #unittest
What does select_related do in Django?

select_related does a join in case needed on the DB side and reduce query counts. Let's look at an example:

# Hits the database.
e = Entry.objects.get(id=5)

# Hits the database again to get the related Blog object.
b = e.blog


In the above code 2 queries are issued in DB side. First it gets Entry record and then blog is fetched from DB when e.blog is called. And here’s select_related lookup:

# Hits the database.
e = Entry.objects.select_related('blog').get(id=5)

# Doesn't hit the database, because e.blog has been prepopulated
# in the previous query.
b = e.blog


You can follow foreign keys in a similar way to querying them. If you have the following models:

from django.db import models

class City(models.Model):
# ...
pass

class Person(models.Model):
# ...
hometown = models.ForeignKey(
City,
on_delete=models.SET_NULL,
blank=True,
null=True,
)

class Book(models.Model):
# ...
author = models.ForeignKey(Person, on_delete=models.CASCADE)


Then a call to Book.objects.select_related('author__hometown').get(id=4) will cache the related Person and the related City:

# Hits the database with joins to the author and hometown tables.
b = Book.objects.select_related('author__hometown').get(id=4)
p = b.author # Doesn't hit the database.
c = p.hometown # Doesn't hit the database.

# Without select_related()...
b = Book.objects.get(id=4) # Hits the database.
p = b.author # Hits the database.
c = p.hometown # Hits the database.


#python #django #select_related #join #database #models