Writing your first contribution for Django

Introduzione

Ti interessa restituire qualcosa alla comunità? Potresti avere trovato un bug in Django che ti piacerebbe vedere corretto, o ci potrebbe essere una piccola funzionalità che vorresti fosse aggiunta.

Contribuire a Django è il miglior modo per affrontare le tue preoccupazioni. All’inizio questo può scoraggiare ma si tratta di un percorso «battuto» con la documentazione, i tool e la community, che ti supporta. Ti accompagneremo nell’intero processo, in modo che tu possa apprendere con degli esempi.

Per chi è questo tutorial?

Vedi anche

Se cerchi riferimenti sui dettagli per contribuire al codice, vedi la documentazione Writing code

For this tutorial, we expect that you have at least a basic understanding of how Django works. This means you should be comfortable going through the existing tutorials on writing your first Django app. In addition, you should have a good understanding of Python itself. But if you don’t, Dive Into Python is a fantastic (and free) online book for beginning Python programmers.

Quelli di voi che non hanno familiarità con i sistemi di controllo di versione e con Trac troveranno che questo tutorial e i suoi link includono le informazioni necessarie per cominciare. Comunque, se prevedete di contribuire a Django regolarmente, probabilmente vorrete leggere di più riguardo questi strumenti.

Nelle intenzioni, questo tutorial tenta di spiegare il più possibile, per essere di aiuto alla maggior parte dei lettori.

Dove trovare aiuto:

If you’re having trouble going through this tutorial, please post a message on the Django Forum, django-developers, or drop by `#django-dev on irc.libera.chat`__ to chat with other Django users who might be able to help.

Di che parla questo tutorial?

We’ll be walking you through contributing to Django for the first time. By the end of this tutorial, you should have a basic understanding of both the tools and the processes involved. Specifically, we’ll be covering the following:

  • Installazione di Git.
  • Scarica una copia della versione di sviluppo di Django
  • Eseguire la suite di test di Django.
  • Writing a test for your changes.
  • Writing the code for your changes.
  • Testing your changes.
  • Mandare una pull request.
  • Dove cercare per ulteriori informazioni.

Una volta terminato il tutorial, puoi dare un’occhiata al resto della Django’s documentation on contributing. Contiene moltissime informazioni utili ed è una lettura imperdibile per chiunque voglia contribuire regolarmente a Django. Se hai delle domande, li probabilmente ci sono le risposte.

E” necessario Python 3!

La versione correnti di Django non sopporta Python 2.7. Scarica Python 3 da Python’s download page oppure attraverso il packet manager del tuo sistema operativo.

Per gli utenti Windows

Vedi Installa Python sulla documentazione di Windows per una guida aggiuntiva.

Codice di Condotta

Come contributor, puoi aiutarci a tenere la Django community open e inclusa. Per favore leggi e segui i nostri Code of Conduct.

Installazione di Git

For this tutorial, you’ll need Git installed to download the current development version of Django and to generate a branch for the changes you make.

Per verificare se hai installato Git, inserisci «git» nella riga di commando. Se ricevi come risposta che questo commando non può essere trovato, dovrai scaricarlo ed installarlo, vai alla «pagina del download di Git»__.

Se non hai molta confidenza con Git, puoi sempre trovare informazioni riguardo ai suoi comandi (una volta installato) digitando «git help» nella riga di commando.

Ottenere una copia della versione di sviluppo di Django

Il primo passo per contribuire a Django è ottenere una copia del codice sorgente. Prima, fare il fork : fork Django on GitHub. Dopo, dalla riga di commando, utilizza il comando «cd» per navigare fino alla directory dove vorrai posizionare la tua copia locale di Django.

Scaricare la repository del codice sorgente Django usando il seguente comando

$ git clone https://github.com/YourGitHubName/django.git
...\> git clone https://github.com/YourGitHubName/django.git

Connessione lenta?

Puoi aggiungere l’argomento «–depth 1» a «git clone» per saltare il download della cronologia commit di Django che riduce il trasferimento di dati da ~250 MB a ~70 MB.

Ora che hai una copia in locale di Django, puoi installarlo come installeresti qualunque altro pacchetto usando pip. Il modo più pratico per farlo è usando un ambiente virtuale, ovvero una feature all’interno di Python che ti permette di tenere separata una cartella di ogni pacchetto installato per ognuno dei tuoi progetti cosicché non interferiscano tra loro.

È una buona idea mantenere tutti i tuoi ambienti virtuali in un unico posto, per esempio in .virtualenvs/ all’interno della home.

Crea un nuovo ambiente virtuale avviando:

$ python3 -m venv ~/.virtualenvs/djangodev
...\> py -m venv %HOMEPATH%\.virtualenvs\djangodev

Il percorso è dove il nuovo environment verrà salvato sul tuo computer.

Il passaggio finale nel settare il tuo ambiente virtuale è attivare:

$ source ~/.virtualenvs/djangodev/bin/activate

Se il commando source non è disponibile, puoi invece usare un punto:

$ . ~/.virtualenvs/djangodev/bin/activate

Devi attivare il virtual environment tutte le volte che apri una nuova finestra del terminale.

Per gli utenti Windows

Per attivare il tuo ambiente virtuale su Windows, avvia:

...\> %HOMEPATH%\.virtualenvs\djangodev\Scripts\activate.bat

Il nome dell’ambiente virtuale attualmente attivo è mostrato sulla linea di comando per aiutarti a tenere in mente quale stai usando. Tutto ciò che installi usando «pip» mentre questo nome è mostrato verrà installato in quell’ambiente virtuale, isolato da altri ambienti e dai pacchetti del sistema.

Procedi e installa la copia precedentemente clonata di Django:

$ python -m pip install -e /path/to/your/local/clone/django/
...\> py -m pip install -e \path\to\your\local\clone\django\

The installed version of Django is now pointing at your local copy by installing in editable mode. You will immediately see any changes you make to it, which is of great help when writing your first contribution.

Creazione di progetti con una copia locale di Django

It may be helpful to test your local changes with a Django project. First you have to create a new virtual environment, install the previously cloned local copy of Django in editable mode, and create a new Django project outside of your local copy of Django. You will immediately see any changes you make to Django in your new project, which is of great help when writing your first contribution, especially if testing any changes to the UI.

You can follow the tutorial for help in creating a Django project.

Eseguire la suite di test di Django per la prima volta

Quando contribuisci a Django, è molto importante che i cambiamenti che apporti al codice non introducano bug in altre aree di Django. Un modo di controllare che Django funzioni ancora dopo aver apportato i cambiamenti è quello di lanciare la suite di test di Django. Se tutti i test hanno successo, allora puoi essere ragionevolmente sicuro che i tuoi cambiamenti funzionino e che non hai pregiudicato la funzionalità di altre parti di Django. Se non hai mai lanciato la suite di test di Django, è una buona idea lanciarla prima per cominciare ad avere familiarità con i suoi output.

Prima di lanciare la suite di test, entra nella directory tests/ di Django usando il comando cd tests ed installa le dipendenze per i test, lanciando:

$ python -m pip install -r requirements/py3.txt
...\> py -m pip install -r requirements\py3.txt

Se incontri un errore durante l’installazione, al tuo sistema potrebbe mancare una dipendenza per uno o più package Python. Consulta la documentazione del package per il quale si verifica l’errore o cerca nel web il messaggio di errore che ti si è presentato.

Ora siamo pronti per far partire la nostra suite di test. Se stai usando GNU/Linux, macOS, o altre variazioni di Unix, esegui:

$ ./runtests.py
...\> runtests.py 

Adesso siedi e rilassati. L’intera suite di test di Django si compone di centinaia di test e ci vorrà qualche minuto perchè giri, dipendentemente dalla velocità del tuo computer.

Mentre la suite di test di Django è in esecuzione, vedrai scorrere lettere rappresentanti lo stato di ogni test man mano che viene completato. «E» indica che un errore è stato trovato, e «F» indica che le asserzioni del test sono fallite. Entrambi i casi sono considerati come fallimenti. Nel mentre, «x» e «s» hanno indicato probabili fallimenti e test omessi. I punti indicano i test passati.

Quando i test vengono saltati, questo accade a causa di librerie mancanti necessarie per eseguire il test; guarda Running all the tests per la lista delle dipendenze e assicurati di installare quelle relative ai test delle modifiche che stai facendo (non ne avremo bisogno in questa guida). Alcuni test sono per specifiche banche dati e verranno saltati se non state utilizzando quelle relative ad essi. SQLite è la banca dati di default. Per eseguire i test usandone una differente, guarda Using another settings module.

Una volta che il test è terminato, dovresti venir salutato con un messaggio che ti informa se la suite di test ha avuto successo o ha fallito. Poichè non hai ancora fatto modifiche al codice Django, l’intera suite di test dovrebbe aver successo. Se invece fallisce o dà errore assicurati di aver seguito tutti i passaggi precedenti correttamente. Guarda Running the unit tests per ulteriori informazioni.

Considera che l’ultima versione del ramo «main» potrebbe non essere sempre stabile. Quando sviluppi basandoti su «main», puoi controllare `Django's continuous integration builds`__ per determinare se i fallimenti sono relativi alla tua macchina o sono presenti nella build ufficiale di Django. Se controlli una build specifica, puoi vedere la sezione «Configuration Matrix» che mostra i fallimenti dovuti alla versione di Python e al database utilizzato.

Nota

For this tutorial and the ticket we’re working on, testing against SQLite is sufficient, however, it’s possible (and sometimes necessary) to run the tests using a different database. When making UI changes, you will need to run the Selenium tests.

Lavorare su una funzionalità

Per questa guida, lavoreremo su un «ticket falso» come caso di studio. Queste sono le ipotesi:

Ticket #99999 – Permette di fare un toast

Django dovrebbe avere a disposizione una funzione «django.shortcuts.make_toast()» che ritorna «toast».

Aggiungeremo ora questa funzionalità e i test associati.

Creating a branch

Prima di fare qualsiasi modifica, crea una nuova branch per il ticket:

$ git checkout -b ticket_99999
...\> git checkout -b ticket_99999

Puoi scegliere qualunque nome che desideri per il ramo, «ticket_99999» è un esempio. Tutte le modifiche fatte su questo ramo saranno specifiche per il ticket e non andranno a modificare la copia principale del codice che abbiamo clonato in precedenza.

Scrivere alcuni test per il tuo ticket

In most cases, for a contribution to be accepted into Django it has to include tests. For bug fix contributions, this means writing a regression test to ensure that the bug is never reintroduced into Django later on. A regression test should be written in such a way that it will fail while the bug still exists and pass once the bug has been fixed. For contributions containing new features, you’ll need to include tests which ensure that the new features are working correctly. They too should fail when the new feature is not present, and then pass once it has been implemented.

A good way to do this is to write your new tests first, before making any changes to the code. This style of development is called `test-driven development`__ and can be applied to both entire projects and single changes. After writing your tests, you then run them to make sure that they do indeed fail (since you haven’t fixed that bug or added that feature yet). If your new tests don’t fail, you’ll need to fix them so that they do. After all, a regression test that passes regardless of whether a bug is present is not very helpful at preventing that bug from reoccurring down the road.

Ora vediamo il nostro esempio.

Scrivere un test per il ticket #99999

Per risolvere questo ticket, aggiungeremo una funzione make_toast() al modulo django.shortcuts. Prima, scriveremo un test che usa la funzione e controlla che il suo output sia corretto.

Naviga fino alla cartella di Django «tests/shortcuts/» e crea un nuovo file «test_make_toast.py». Aggiungi il seguente codice:

from django.shortcuts import make_toast
from django.test import SimpleTestCase


class MakeToastTests(SimpleTestCase):
    def test_make_toast(self):
        self.assertEqual(make_toast(), "toast")

Questo test controlla che «make_toast()» ritorna «toast».

Ma questa cosa del testing sembra una cosa difficile…

Se non hai mai avuto a che fare con i test prima d’ora, potranno sembrarti un po” difficili da scrivere a prima vista. Per fortuna, fare i test è davvero un grande argomento nella programmazione, quindi ci sono molte informazioni:

  • Per iniziare a scrivere test per Django, un buon primo passo è leggere i documenti in Writing and running tests.
  • Buttati Into Python ( un libro online gratuito per i principianti sviluppatori di Python ) include alcuni ottimi progetti come `introduction to Unit Testing`__.
  • Dopo aver letto queste cose, se vuoi qualcosa di più succulento per i tuoi denti, c’è sempre la documentazione Python unittest

Eseguire il tuo nuovo test

Poichè non abbiamo fatto ancora alcuna modifica a «django.shortcuts», il nostro test dovrebbe fallire. Eseguiamo tutti i test nella cartella «shortcuts» per assicurarci che è proprio ciò che sta accadendo. «cd» nella cartella di Django «tests/» ed esegui:

$ ./runtests.py shortcuts
...\> runtests.py shortcuts

If the tests ran correctly, you should see one failure corresponding to the test method we added, with this error:

ImportError: cannot import name 'make_toast' from 'django.shortcuts'

Se tutti i test vengono superati, assicurati di aggiungere il test mostrato in precedenza nella cartella e con il nome file appropriati.

Scrivere il codice per il tuo ticket

Successivamente aggiungeremo la funzione make_toast().

Vai alla cartella django/ ed apri il file shortcuts.py. Alla fine, aggiungi:

def make_toast():
    return "toast"

Ora dobbiamo assicurarci che il test che abbiamo scritto in precedenza venga superato, quindi possiamo vedere se il codice che abbiamo scritto funziona correttamente. Ancora una volta, posizionati nella cartella Django tests/ ed esegui:

$ ./runtests.py shortcuts
...\> runtests.py shortcuts

Tutto dovrebbe funzionare. In caso contrario, assicurati di aver aggiunto la funzione al file corretto.

Eseguire la suite di test di Django per la seconda volta

Once you’ve verified that your changes and test are working correctly, it’s a good idea to run the entire Django test suite to verify that your change hasn’t introduced any bugs into other areas of Django. While successfully passing the entire test suite doesn’t guarantee your code is bug free, it does help identify many bugs and regressions that might otherwise go unnoticed.

Per eseguire l’intera suite test di Django, a riga di commando esegui``cd`` nella cartella tests/ di Django ed esegui:

$ ./runtests.py
...\> runtests.py 

Scrivere la Documentazione

This is a new feature, so it should be documented. Open the file docs/topics/http/shortcuts.txt and add the following at the end of the file:

``make_toast()``
================

.. function:: make_toast()

.. versionadded:: 2.2

Returns ``'toast'``.

Since this new feature will be in an upcoming release it is also added to the release notes for the next version of Django. Open the release notes for the latest version in docs/releases/, which at time of writing is 2.2.txt. Add a note under the «Minor Features» header:

:mod:`django.shortcuts`
~~~~~~~~~~~~~~~~~~~~~~~

* The new :func:`django.shortcuts.make_toast` function returns ``'toast'``.

Per avere ulteriori informazione riguardo la scrittura della documentazione, includendo una spiegazione di cosa sia versionadded, controlla Writing documentation. Quella pagina include una spiegazione di come creare una copia della documentazione in locale, in modo da poter avere un’anteprima dell’HTML che verrà generato.

Visualizzare l’anteprima delle tue modifiche

Now it’s time to review the changes made in the branch. To stage all the changes ready for commit, run:

$ git add --all
...\> git add --all

Mostra le differenze tra la tua copia attuale di Django ( con le tue modifiche ) e la revisione di quello che avevi scaricato seguendo la guida.

$ git diff --cached
...\> git diff --cached

Usa le freccettine per muoverti su e giu.

diff --git a/django/shortcuts.py b/django/shortcuts.py
index 7ab1df0e9d..8dde9e28d9 100644
--- a/django/shortcuts.py
+++ b/django/shortcuts.py
@@ -156,3 +156,7 @@ def resolve_url(to, *args, **kwargs):

     # Finally, fall back and assume it's a URL
     return to
+
+
+def make_toast():
+    return 'toast'
diff --git a/docs/releases/2.2.txt b/docs/releases/2.2.txt
index 7d85d30c4a..81518187b3 100644
--- a/docs/releases/2.2.txt
+++ b/docs/releases/2.2.txt
@@ -40,6 +40,11 @@ database constraints. Constraints are added to models using the
 Minor features
 --------------

+:mod:`django.shortcuts`
+~~~~~~~~~~~~~~~~~~~~~~~
+
+* The new :func:`django.shortcuts.make_toast` function returns ``'toast'``.
+
 :mod:`django.contrib.admin`
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~

diff --git a/docs/topics/http/shortcuts.txt b/docs/topics/http/shortcuts.txt
index 7b3a3a2c00..711bf6bb6d 100644
--- a/docs/topics/http/shortcuts.txt
+++ b/docs/topics/http/shortcuts.txt
@@ -271,3 +271,12 @@ This example is equivalent to::
         my_objects = list(MyModel.objects.filter(published=True))
         if not my_objects:
             raise Http404("No MyModel matches the given query.")
+
+``make_toast()``
+================
+
+.. function:: make_toast()
+
+.. versionadded:: 2.2
+
+Returns ``'toast'``.
diff --git a/tests/shortcuts/test_make_toast.py b/tests/shortcuts/test_make_toast.py
new file mode 100644
index 0000000000..6f4c627b6e
--- /dev/null
+++ b/tests/shortcuts/test_make_toast.py
@@ -0,0 +1,7 @@
+from django.shortcuts import make_toast
+from django.test import SimpleTestCase
+
+
+class MakeToastTests(SimpleTestCase):
+    def test_make_toast(self):
+        self.assertEqual(make_toast(), 'toast')

When you’re done previewing the changes, hit the q key to return to the command line. If the diff looked okay, it’s time to commit the changes.

Committing the changes

Per confermare le modifiche:

$ git commit
...\> git commit

Questo apre l’editor di test per inserire il messaggio di commit. Segui le linee guida del :ref:”messaggio di commit<committing-guidelines>” e scrivi un messaggio tipo:

Fixed #99999 -- Added a shortcut function to make toast.

Inviare il commit e creare una pull request

After committing the changes, send it to your fork on GitHub (substitute «ticket_99999» with the name of your branch if it’s different):

$ git push origin ticket_99999
...\> git push origin ticket_99999

Puoi creare una pull request vistando la Django GitHub page. Vedrai il tuo branch nella sezione «Your recently pushed branches». Clicca «Compare & pull request» di fianco.

Please don’t do it for this tutorial, but on the next page that displays a preview of the changes, you would click «Create pull request».

Prossimi passi

Congratulazioni, hai imparato a fare una richiesta pull a Django! Dettagli su tecniche più avanzate di cui potresti aver bisogno sono in Working with Git and GitHub.

Ora puoi utilizzare queste conoscenze aiutando a migliorare il codice di Django.

Maggiori informazioni per nuovi contributori

Before you get too into contributing to Django, there’s a little more information on contributing that you should probably take a look at:

  • You should make sure to read Django’s documentation on claiming tickets and submitting pull requests. It covers Trac etiquette, how to claim tickets for yourself, expected coding style (both for code and docs), and many other important details.
  • Chi vuole contribuire per la prima volta dovrebbe anche leggere la :doc:”documentazione per i nuovi contributori</internals/contributing/new-contributors/>” di Django. E” piena di buoni consigli per quelli di noi che sono nuovi nell’aiutare con Django.
  • Dopo questi, se sei ancora in cerca di altre informazioni sul contribuire, puoi sempre cercare nel resto della :doc:”documentazione di Django sul contribuire</internals/contributing/index>”. Contiene molte informazioni utili e dovrebbe essere la tua prima fonte di informazione per rispondere alle domande che potresti avere.

Cercare il tuo primo vero ticket

Once you’ve looked through some of that information, you’ll be ready to go out and find a ticket of your own to contribute to. Pay special attention to tickets with the «easy pickings» criterion. These tickets are often much simpler in nature and are great for first time contributors. Once you’re familiar with contributing to Django, you can start working on more difficult and complicated tickets.

If you just want to get started already (and nobody would blame you!), try taking a look at the list of `easy tickets without a branch`__ and the `easy tickets that have branches which need improvement`__. If you’re familiar with writing tests, you can also look at the list of `easy tickets that need tests`__. Remember to follow the guidelines about claiming tickets that were mentioned in the link to Django’s documentation on claiming tickets and submitting branches.

Cosa fare dopo aver creato una pull request?

After a ticket has a branch, it needs to be reviewed by a second set of eyes. After submitting a pull request, update the ticket metadata by setting the flags on the ticket to say «has patch», «doesn’t need tests», etc, so others can find it for review. Contributing doesn’t necessarily always mean writing code from scratch. Reviewing open pull requests is also a very helpful contribution. See Triaging tickets for details.

Back to Top