Postagens

Mostrando postagens de agosto, 2026

Django: Como usar o Shell ?

 Você usa o comando `django-shell`   python manager.py shell na pasta do seu projeto para iniciar o Django Shell. O Django Shell é simplesmente um shell Python, mas com todo o código da sua aplicação já carregado. Portanto, você pode executar instruções Django, assim como instruções Python. Exemplo de sessão: bash $ python manage.py shell >>> from myapp.models import User >>> User.objects.all() <QuerySet [<User: Alice>, <User: Bob>]> >>> new_user = User(name= "Charlie" ) >>> new_user.save() python manage.py shell Python 3.9.5 (default, May 27 2021, 19:45:35) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> print('Hello world') Hello world >>> from polls.models import Question >>> q = Question(question_text='Hel...

Django's annotate and aggregate methods

  Agregação >>> Book.objects.aggregate(average_price=Avg('price')) {'average_price': 34.35} Retorna um dicionário contendo o preço médio de todos os livros no queryset. Anotação >>> q = Book.objects.annotate(num_authors=Count('authors')) >>> q[0].num_authors 2 >>> q[1].num_authors 1 q é o conjunto de livros, mas cada livro foi anotado com o número de autores.

Python Requests

 Material de apoio https://www.digitalocean.com/community/tutorials/how-to-get-started-with-the-requests-library-in-python-pt https://requests.readthedocs.io/pt_BR/latest/user/quickstart.html https://realpython.com/python-requests/ https://pythonhelp.wordpress.com/2013/03/12/acessando-recursos-na-web-com-python/

Models - Django

  Recomendação de boas práticas https://steelkiwi.com/blog/best-practices-working-django-models-python/ Lista de opções YEAR_IN_SCHOOL_CHOICES = ( (u'FR', u'Freshman'), (u'SO', u'Sophomore'), (u'JR', u'Junior'), (u'SR', u'Senior'), (u'GR', u'Graduate'), ) Por exemplo: from django.db import models class Person(models.Model): GENDER_CHOICES = ( (u'M', u'Male'), (u'F', u'Female'), ) name = models.CharField(max_length=60) gender = models.CharField(max_length=2, choices=GENDER_CHOICES) Campos de chave primária automáticos Por padrão, o Django dá a cada model o seguinte campo: id = models.AutoField(primary_key=True) Esta é uma chave primária auto incremental. Nesse exemplo, o nome por extenso é "Person's first name" : first_name = models.CharField("Person's first name", max_length=30) Nesse exemplo, o n...

Manage Files - Django

  File Opening Modes There are modes in which you can open a file in Python. The mode you choose depends on how you plan to use the file, or what kind of data you'll be reading (writing) from (to) the file. This mode is specified when opening a file using the built-in open() method, explained in further detail in the next section. Let's take a look at some of the possible combinations of file modes: w: Opens a file for writing and creates a new file if it doesn't yet exist. In the case that the file does exist, it overwrites it. w+: Opens a file for writing but also for reading and creating it if it doesn't exist. If a file already exists, it overwrites it. r: Opens a file for reading only. rb: Opens a file for reading in Binary format. wb: Opens a file for writing in Binary format. wb+: Opens a file for writing and reading in Binary format. a: Opens a file for appending at the end of the file. +: In general, this character is used along side r , w , or a and means bo...

Django Messages

  Django messages tags messages.debug(request, '%s SQL statements were executed.' % count) messages.info(request, 'Three credits remain in your account.') messages.success(request, 'Profile details updated.') messages.warning(request, 'Your account expires in three days.') messages.error(request, 'Document deleted.') Create a messages template #env > mysite > main > templates > main > includes > (New File) messages.html {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} {% block messages %} <ul class="messages" id="messages-list"> {% if messages %} {% for message in messages %} <li> {% if message.tags %} <div class="alert alert-{...

Django Cache

 Django caching https://testdriven.io/blog/django-caching/ https://realpython.com/caching-in-django-with-redis/ Redis https://www.digitalocean.com/community/tutorials/how-to-install-and-secure-redis-on-ubuntu-20-04-pt << ler material para verificar questões de segurança. https://www.tutorialspoint.com/redis/index.htm

Como adicionar um ffeito de animação durante o carregamento da página

  https://medium.com/@nandraj.rathod.009/how-to-add-page-loading-animation-in-django-app-dd0e83f46540

Class Based View

 Artigo bem completo sobre o tema: http://pythonclub.com.br/class-based-views-django.html

Cron Job - Django

  A parte principal de um cron é sua sintaxe de tempo, que define a programação na qual o trabalho deve ser executado periodicamente. Consiste em cinco partes ordenadas, ou seja, começando do minuto até a definição do dia da semana. Minuto (0 - 59) Hora (0 - 23) Dia do mês (1 - 31) Mês (1 - 12) Dia da semana (0 - 6) A sintaxe mais simplificada para um cron pode ser vista como * * * * * [trabalho] Para cada campo, usamos um asterisco (*) que indica todos os números possíveis para uma posição. O cron job acima está programado para ser executado a cada minuto. Vamos ver mais alguns exemplos para entender melhor 2 * * * * [trabalho] A definição de tempo acima implica que o trabalho está programado para ser executado a 2 minutos de cada hora, ou seja, 00:02, 01:02, 02:02, 03:02 etc. 10 8 * * * [trabalho] A sintaxe acima corresponde ao cronograma de trabalho às 8:10 de cada dia * / 2 * * 3 * [trabalho] Agora, isso é algo diferente. Aqui, usamos o operador “/” (divisão). Você pode notar q...