Writing your first contribution for Django¶
Introduzione¶
Interested in giving back to the community a little? Maybe youâve found a bug in Django that youâd like to see fixed, or maybe thereâs a small feature you want added (but remember that proposals for new features should follow the process for suggesting new features).
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 Contributing 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 or drop by the Django Discord server 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.
Once youâre done with the tutorial, you can look through the rest of Djangoâs documentation on contributing. It contains lots of great information and is a must-read for anyone whoâd like to become a regular contributor to Django. If youâve got questions, itâs probably got the answers.
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?
You can add the --depth 1 argument to git clone to skip downloading
all of Djangoâs commit history, which reduces data transfer from ~250 MB
to ~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 testing your first contribution.
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.
Now we are ready to run the test suite:
$ ./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.
While Djangoâs test suite is running, youâll see a stream of characters
representing the status of each test as it completes. E indicates that an
error was raised during a test, and F indicates that a testâs assertions
failed. Both of these are considered to be test failures. Meanwhile, x and
s indicate expected failures and skipped tests, respectively. Dots indicate
passing tests.
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.
Working on an approved new feature¶
For this tutorial, weâll work on a «fake accepted ticket» as a case study. Here are the imaginary details:
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:: 6.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 6.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/6.2.txt b/docs/releases/6.2.txt
index 7d85d30c4a..81518187b3 100644
--- a/docs/releases/6.2.txt
+++ b/docs/releases/6.2.txt
@@ -34,6 +34,11 @@
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:: 6.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.