Python Django Tutorial (2023)

Python öffnet die Türen zu so ziemlich allen Bereichen: Desktop-Anwendungen mit PyQt, Handy-Apps mit Kivy oder gar Mikrocontroller wie den Raspberry Pi Pico mit MicroPython. Im Bereich Webanwendungen ist Python Django dabei das bekannteste Framework. Wie das vergleichbareRuby on Railssetzt Django auf Templates und eine saubere Architektur. Das Framework eignet sich für schnelles Prototyping und glänzt zudem durch die hervorragende Datenbankanbindung. Dieser Beitrag hilft bei den ersten Schritten.

Inhaltsverzeichnis

  1. Installation von Python Django
  2. Ein Django-Projekt in Python anlegen
  3. Eine App zu Python Django hinzufügen
  4. MVC vs.MVT
  5. Views
    • Zuerst noch die URL definieren
  6. FAQS zu Python Django

Installation von Python Django

Um mit Python Django zu starten, solltest Du Python 3 bei Dir installiert haben. Am besten checkst Du das noch mal durch Eingabe des Befehlspythonin einem Terminal-Fenster. Anschliend sollte eine Meldung erscheinen, die der folgenden ähnelt:

Python Django Tutorial (1)

Ist das der Fall, kannst Du Python Django installieren. Am einfachsten geht das mitpip, dem Paketmanager, den Du ebenfalls von einem Terminal aus aufrufst:

pip install Django==3.1.6

(Video) Python Django Tutorial for Beginners

Das Framework und die dafür benötigten Abhängigkeiten werden nun heruntergeladen und installiert. Um sicherzustellen, dass die Installation funktionsfähig ist, gibst Du abschließend noch die beiden folgenden Befehle in eine Python-Shell ein:

Python Django Tutorial (2)

Wenn nun eine Versionsnummer ausgegeben wird (die 3.1.6), dann hast Du bereits die erste Django-Methode in Python benutzt und alles ist startklar für die Arbeit mit dem Webframework. Du hast noch Fragen? Dann schau in unserer RubrikPythonvorbei. Doch wer in der digitalisierten Welt nicht nur sein Smartphone bedienen will, sondern auch persönlich die Chancen der Digitalisierung für sich nutzen möchte, ist in unserem Computerkurs genau richtig!

Ein Django-Projekt in Python anlegen

Zunächst benötigen wir ein Python Django-Projekt. Wie bei vielen Frameworks kannst Du es mit einem Kommandozeilenwerkzeug anlegen. Hier heißt esdjango-adminund ist bereits installiert. Die Option zum Anlegen eines neuen Projekts lautetstartproject. Danach kommt dann noch der Name des Projekts. Unser Projekt wird einPIM, also einPersonal Information Manager, mit dem sich Kontakte, Termine, Aufgaben und Notizen verwalten lassen. Ein großes Vorhaben, aber zumindest fangen wir damit mal an. Du willst Dir beim Coding Arbeit sparen? Dann ist die Python For Schleife das Richtige für Dich.

Der Befehl zum Erzeugen des PIM-Projekts lautet also:

django-admin startproject pim

Python Django legt daraufhin einen neuen Ordner mit dem ausgewählten Namen, hierpim,an. Schau Dir die Struktur und Dateien im neuen Projekt in Ruhe an:

Python Django Tutorial (3)

__init__.pyist die Paketdefinition, die Dein Projekt zu einem Paket macht. Insettings.pywerden wichtige Einstellungen für das Projekt vorgenommen. Hier kann man zum Beispiel den Debug-Mode ein- oder ausschalten oder die Datenbank konfigurieren. Wir bearbeiten die Datei später noch. Das gilt auch für die Dateiurls.py, die URL-Konfiguration des Projekts. In ihr legt man fest, was passiert bzw. welcher Code ausgeführt wird, wenn eine bestimmte URL im Browser aufgerufen wird. Die Dateimanage.pyhilft Dir beim Verwalten Deines Projekts. Mit ihr kannst Du zum Beispiel den enthaltenen Entwicklungsserver starten. Dazu wechselst Du im Terminal in den pim-Ordner und gibst den folgenden Befehl ein:

python manage.py runserver

(Video) Python Django Web Framework - Full Course for Beginners

Wenn Du nun im Browser die URLlocalhost:8000aufrufst, meldet sich Python Django mit einer ersten Website, die uns bestätigt, dass soweit alles funktioniert: Hervorragend!

Python Django Tutorial (4)

Eine App zu Python Django hinzufügen

In vielen anderen Frameworks könntest Du nun direkt mit dem Erstellen der ersten Webseite loslegen. Python Django ist da etwas komplizierter und benötigt zunächst noch eineAppim Projekt. Eine App ist ein Untermodul des Projekts, bei uns also zum BeispielTermineoderNotizen. Du legst die App wieder mitmanage.pyan. Diesmal aber mit der Optionstartapp, gefolgt vom Namen der zu erzeugenden App. Hier heißt sietermine:

python manage.py startapp termine

Im Ordnerpimfindet sich nun ein neuer Ordnertermine.Er ist folgendermaßen aufgebaut:

Python Django Tutorial (5)

Eine ganze Menge Dateien inzwischen, oder? Zum Glück müssen wir nicht alle bearbeiten. Denn innerhalb der App sind besonders die Dateienviews.pyundmodels.pywichtig, die wir bald mit Code befüllen.

MVC vs.MVT

Die meisten Webframeworks basieren auf dem MVC-Pattern. Falls Du Patterns noch nicht kennst: Ein Pattern (auf deutsch Entwurfsmuster) ist eine Idee, ein Konzept wie etwas programmiert werden könnte. Eine Art Kochrezept also, das man dann in verschiedenen Programmiersprachen ausprogrammieren kann. MVC ist vermutlich das bekannteste Pattern, die Abkürzung steht fürModel,ViewundController. Die Idee hinter MVC ist, dass eine Softwarekomponente namens Controller eine Anfrage aus dem Web entgegennimmt. Zum Beispiel, weil auf der Webseite ein Button gedrückt und dadurch ein HTTP-Request verschickt wurde. Der Controller aktualisiert mithilfe eventuell übergebener Daten den Datenbestand im Hintergrund (das Model), sucht bei Bedarf benötigte Daten heraus und liefert dann eine neue Webseite (die View) an den Benutzer aus.

Python Django basiert auf dieser Idee, allerdings in leicht abgewandelter Form. In Django musst Du keinen Controller schreiben, das Framework kümmert sich selber darum. In der View wird die Geschäftslogik ausgeführt, mit dem Model interagiert und dann als Ergebnis ein Template mit HTML-Code gerendert. Das Ganze nennt sich dann MVT. Klingt kompliziert? Keine Panik, wir schauen uns das jetzt am Beispiel an und dann wird es klar.

(Video) Python Django 7 Hour Course

Views

Die Datei views.py ist die View derTermine-App. Hier kommt der HTTP-Request an, wird verarbeitet und die Antwort formuliert. Im folgenden Beispiel wird in der Funktionindexeinfach ein erster Termin als HTTP-Response an den Aufrufer, also den Browser, geliefert:

Python Django Tutorial (6)

Wenn Du nun den Entwicklungsserver wieder startest und localhost:8000 aufrufst, stellst Du fest, dass es noch nicht geht. Es fehlt noch etwas. Wir haben zwar definiert, was die View zurückgeben soll, aber noch nicht festgelegt bei Aufruf welcher Adresse, die Antwort angezeigt werden soll.

Zuerst noch die URL definieren

In der URL-Konfiguration der App (das ist die Datei termine/urls.py, sie muss noch angelegt werden) definieren wir, dass bei Aufruf der App ohne weitere Pfadangabe (deshalb die leeren Anführungszeichen in der Klammer hinter path), die Funktionindexausviewsaufgerufen wird:

Python Django Tutorial (7)

In der URL-Konfiguration der App (das ist die Datei termine/urls.py, sie muss noch angelegt werden) definieren wir, dass bei Aufruf der App ohne weitere Pfadangabe (deshalb die leeren Anführungszeichen in der Klammer hinter path), die Funktionindexausviewsaufgerufen wird:

Auch das Projekt hat eine URL-Konfiguration (pim/urls.py). In ihr wird bei Aufruf von /termine auf urls.py der Termine-App verwiesen. Insgesamt legen wir auf diese, zugegebenermaßen etwas umständliche, Weise also fest, dass bei Aufruf von /termine die Funktion views.index ausgeführt und somit der Termin angezeigt werden soll.

Python Django Tutorial (8)

Nach diesen Änderungen wird der Termin bei Aufruf von der Adresselocalhost:8000/terminenun im Browser angezeigt! Die URL-Konfiguration mit mehreren Dateien ist nicht ganz einfach, aber sehr flexibel. Die Apps sind komplett eigenständige Module, die zudem bei Bedarf in einem anderen Projekt verwendet werden könnten. Das Zufügen von weiteren Funktionen mit zugehörigen URL-Patterns oder ganzen Apps ist denkbar einfach, alles hat seinen festen Platz.

Einige Bestandteile von Python Django, wie Projekt, Apps, Views und URL-Konfigurationen, hast Du nun kennengelernt. Sicher hast Du auch eine erste Idee davon bekommen, wie sie zusammenhängen. Im nächsten Teil des Tutorials beschäftigen wir uns mit der Datenbank, Datenmodellen, Migrationen und den Templates, sprich HTML.Es bleibt also spannend! Django ist übrigens mittlerweile so beliebt, dass an der Technischen Universität Chemnitz Einführungskurse zu diesem Webframework stattfinden.

FAQS zu Python Django

Wozu wird Python Django verwendet?

Python Django wird für die schnelle Entwicklung von Websites verwendet. Du kannst Deiner Kreativität dabei freien Lauf lassen und das Tool für vielseitige Projekte einsetzen. Zum Beispiel kannst Du eine Website entwickeln, auf der die Benutzer ein Quiz spielen oder eine Django Chat App entwerfen. Du willst doch erst die Basics üben? Dann schau Dir die Python while Schleife an.

(Video) Django For Beginners - Full Tutorial

Muss man für die Arbeit mit Django bereits Python können?

Bevor Du Dein erstes Django-Projekt startest, solltest Du Dich schon mit Python auskennen. In unseren Kursen zeigen wir Dir, wie derPython Downloadfunktioniert und helfen Dir bei den ersten Schritten. Dein erstes Projekt kannst Du anschließend mit derPython IDLEausführen.

Welche bekannten Websites wurden mit Python Django entwickelt?

Viele bekannte Websites nutzen das Webframework Django. Beispiele für populäre Seiten sind etwa Instagram und Pinterest. Du bekommst nicht genug vom Coden? Dann sieh Dir unseren Artikel zuPyCharman. Das ist alles noch etwas zu kompliziert für Dich? Kein Problem, denn einfache Projekte lassen sich auch mitScratch erstellen.

FAQs

Is Python Django hard to learn? ›

Django is not the easiest tool to learn. It requires a strong foundational knowledge of Python and particularly good familiarity with classes and Object-Oriented Programming.

What is Django used for in Python? ›

Django is a high-level Python web framework that enables rapid development of secure and maintainable websites. Built by experienced developers, Django takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel.

Is Django good for beginners? ›

Django is not a programming language; it is a coding framework built to be compatible with Python — which is a back end coding language. Learning Django can be immensely beneficial for anyone aspiring to become a programmer or web developer.

Is it possible to learn Django in a week? ›

Django is a high-level Python web framework used to build websites and web applications rapidly and securely. Web Developers, Python Developers, and Data Scientists use Django. It takes the average learner between one to four weeks to learn Django.

Do professionals use Django? ›

Django is a Python-based web framework giving developers the tools they need for rapid, hassle-free development. You can find that several major companies employ Django for their development projects. Here are 9 global companies using Django: Instagram.

Is HTML required for Django? ›

Yes, it's highly recommended in case you are developing a webapp. No, if you are developing a REST API or web service using Flask/Django. If you're going to develop web applications, then yes. HTML/CSS are the languages that web browsers understand, so its a necessity.

Is Django is backend or frontend? ›

Is Django frontend or backend? Django is an open-source framework for backend web applications based on Python — one of the top web development languages.

Is Django a full stack? ›

A high-level Python web framework called Django facilitates quickly creating safe and dependable websites. Since it is a full-stack framework, all essential functionalities are provided by default rather than as separate modules.

Is Django the same as SQL? ›

Django and SQL are not replacements for one another, Django is a web framework as a whole, designed to develop web applications, and SQL is a language to query databases.

Can I learn Django in a month? ›

How Long Does it Take to Learn Python Django? It will take you about three months to master the basics of Django. But, you could create your first Django application within a day of getting started. To get started with Django, you'll need a solid understanding of the Python programming language.

Is Django or HTML better? ›

Writting HTML code by hand is very tedious, not very efficient, and limited : you can't make pages that adapts to the person who asks for it such as a user page or a search page. Django is a tool that can understand what a user is asking, and create the HTML code in a fraction of a second, then send it back.

Should I learn Django before SQL? ›

In my opinion, yes. Of course the Django ORM will do most of the job for you when it comes to queries, but you should know SQL. Maybe not every single aspect of SQL but enough to now what you're doing. For instance how can you join two or more tables if you don't know what a join is?

How many hours a day learn coding? ›

We'd recommend somewhere between five and 15 hours per week. If your goal is “learn to code” in a general sense, it can feel overwhelming, and it's almost impossible to know when you've succeeded.

Is Django in demand? ›

Naturally, the demand for Django Developers and Python Developers (with Django skills) remains at an all-time high. Companies look for candidates who've had hands-on Django training and possess a good grip on Python. They usually incline towards candidates who are well-versed in Django, AngularJS, and Spark/Big Data.

Which is the best site to learn Django? ›

5 Best Django Courses to learn Web Development in 2023
  1. Django 3 - Full Stack Websites with Python Web Development. ...
  2. Python and Django Full Stack Web Developer Bootcamp. ...
  3. Django 2.2 & Python | The Ultimate Web Development Bootcamp. ...
  4. Build a Backend REST API with Python & Django - Advanced.

Is NASA using Django? ›

5. NASA. The website of the United States National Aeronautics and Space Administration (NASA) is built using Django.

Is Django getting outdated? ›

Even though Django never got to the same level of popularity as Ruby, it has managed to grow over the years. I've personally been using it for over 15 years. Version 3.1 was recently released as of a few months ago. Some of the largest websites in the world using Django are Instagram, Pinterest & Mozilla.

What skills do I need to learn Django? ›

Django has excellent documentation, and it makes your code much more clean and efficient.
...
In this blog, we are going to discuss 5 essential skills that you should have as a Django developer.
  • System Programming. ...
  • Graphical Interface Creation. ...
  • Web Scripts Development.
Sep 16, 2021

Can you build a website with just Django? ›

Django is a free, open source framework for Python web development and is a very flexible web development tool that can be used to create just about any type of website or app that is needed.

Which is better Flask or Django? ›

In a nutshell, both Flask and Django are popular open-source Python web frameworks. Django is a powerful full-stack framework, whereas Flask is a micro and lightweight framework. There are no set of rules as to what one should use.

Is SQL used in Django? ›

Django officially supports five database management systems: PostgreSQL, MariaDB, MySQL, Oracle, and SQLite (Django, 2020).

What can I make with Django? ›

Top Django Projects To Work On
  • Email Sender Using Django/Python.
  • Login System in Django.
  • Text to HTML Generator.
  • Build a Chat App.
  • Regex Query Tool.
  • Calorie Counter App.
  • Password Safe App.
  • Hospital Management System.

Can Django replace JavaScript? ›

The simple answer is NO. Django is an entirely Python-based web framework, and it is tough for Python to replace JavaScript. First, JavaScript is browser-native, whereas Python is not. Secondly, JavaScript and Python are not web-native, meaning they can work in parallel.

How much do Django developers make? ›

As of April 2022, the average Django developer salary was $107,767 or $52 per hour. However, the highest is $158,000 and the lowest is $68,000.

Where can I practice Django? ›

Udemy Django courses cover all aspects of Django development, whether you're interested in using the framework by itself, or adding it to your fullstack development practice. In this course, we will open the door of the Web development world with Django and try to move deeper.

Which database is best for Django? ›

Postgresql is the preferred database for Django applications due to its open-source nature; and it's also ideal for complex queries.

Is Django a server or database? ›

Django is an extremely popular and fully featured server-side web framework, written in Python. This module shows you why Django is one of the most popular web server frameworks, how to set up a development environment, and how to start using it to create your own web applications.

Which Python is best for Django? ›

What Python version should I use with Django? ¶ Since newer versions of Python are often faster, have more features, and are better supported, the latest version of Python 3 is recommended.

What is the fastest way to learn Django? ›

5 Best Udemy and Coursera Online Courses to learn Django for Web Development
  1. Python Django Dev To Deployment. ...
  2. Django and Python: complete BUNDLE + Django real project 2022. ...
  3. Django: Getting Started. ...
  4. CS 50's Web Programming with Python and JavaScript. ...
  5. Python and Django Full Stack Web Developer Bootcamp.

Do I need to know JavaScript to learn Django? ›

Django is a back-end framework. which is written in python. You only need javascript on the front-end.so it might not be necessary.

Is PyCharm better for Django? ›

As you might already be aware, PyCharm has best-in-class support for the Django web framework.

Do hackers need to learn HTML? ›

If you want to be an ethical hacker of web pages and applications, then you will most likely need to know some HTML and JavaScript. HTML governs the appearance and organization of the web page and is considered a markup language rather than a programming language.

Which frontend is best with Django? ›

Top 10 Front-End and Back-end Frameworks for Full-Stack Developers in 2022
  • Angular [Frontend + JavaScript] ...
  • Node. ...
  • Django [Frontend + Backend + Python] ...
  • Flask [Backend + Python] ...
  • Bootstrap [Frontend + CSS] ...
  • jQuery [Frontend + JavaScript] ...
  • Ruby on Rails [Backend + Ruby] ...
  • GraphQL [Backend + JavaScript]

Why do web developers prefer Django? ›

Django offers a highly secure approach to develop web applications as it prevents attacks like XSS(Cross-Site Scripting), CSRF (Cross-Site Request Forgery), SQL injection, etc.

How many hours does it take to learn Django? ›

If you are an absolute beginner and know nothing about it, then it will take 3 months to cover each Django concept in detail - given you spend 4 hours a day! Now, if you spend a bit of extra time, you can finish it sooner. The only caveat is that before you start learning Django, you must be proficient in Python.

How many days to learn Python? ›

In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.

Can I learn Django without HTML and CSS? ›

No it is not necessary to know html/css, if you are learning Django/Flask. But it depends on which kind of team you are working. If have a large number of people working in your team, you can give the work related to html/css to a specific person specialized in html/css.

Can I learn Django in 3 days? ›

You can learn Django in a couple of weeks, however to become really good at Django you will need time and you will need to build projects. You can even learn Django faster by building following an end to end certification course that also helps you build a project.

Is Django worth learning Python? ›

Yes, Django is python's framework, and it has a wide range of demands with good career scope. It allows users to create apps or websites from an existing source instead of scratch. Django provides you with many job options with good pay. You need to have good knowledge of Django.

What is the best way to learn Django? ›

5 Best Udemy and Coursera Online Courses to learn Django for Web Development
  1. Python Django Dev To Deployment. ...
  2. Django and Python: complete BUNDLE + Django real project 2022. ...
  3. Django: Getting Started. ...
  4. CS 50's Web Programming with Python and JavaScript. ...
  5. Python and Django Full Stack Web Developer Bootcamp.

Are Django developers in demand? ›

Naturally, the demand for Django Developers and Python Developers (with Django skills) remains at an all-time high. Companies look for candidates who've had hands-on Django training and possess a good grip on Python. They usually incline towards candidates who are well-versed in Django, AngularJS, and Spark/Big Data.

Can you make money with Django? ›

The most stable, and probably easiest way to make money with Django is getting a job as a Django Developer. When you have a fulltime job, you can just show up in the morning, do what you are paid to do and when you leave in the afternoon, you don't have to think about it until the next morning.

Do I need to know Javascript to learn Django? ›

Django is a back-end framework. which is written in python. You only need javascript on the front-end.so it might not be necessary.

Is Django still in demand? ›

Oh Yes! Django is still very relevant in 2021, and will most likely be for years to come. Django is one of the most popular web development frameworks in existence, and is based on the very popular programming language Python.

Is Django enough for backend? ›

If you are only interested in building a REST API backend, Django is an overkill. However, you can use the Django REST framework, which is a community-funded project by Encode. It uses Django as the underlying engine by providing a more straightforward interface that is specific to REST API development.

Is Django for frontend or backend? ›

Is Django frontend or backend? Django is an open-source framework for backend web applications based on Python — one of the top web development languages.

What is the disadvantage of Django? ›

One of the main disadvantages or cons of using Django for web app development is it presents a steep and deep learning curve to budding and novice developers and designers. Even though it is a clear and simple framework developed using python language. It can make things difficult to learn for inexperienced developers.

Videos

1. Python Backend Web Development Course (with Django)
(freeCodeCamp.org)
2. Python Django Tutorial: Full-Featured Web App Part 1 - Getting Started
(Corey Schafer)
3. Django Tutorial for Beginners | Full Course
(Telusko)
4. Django For Everybody - Full Python University Course
(freeCodeCamp.org)
5. Build a Social Media App with Django – Python Web Framework Tutorial
(freeCodeCamp.org)
6. Python Django Tutorial: Full-Featured Web App Part 3 - Templates
(Corey Schafer)
Top Articles
Latest Posts
Article information

Author: Aracelis Kilback

Last Updated: 04/10/2023

Views: 6517

Rating: 4.3 / 5 (64 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Aracelis Kilback

Birthday: 1994-11-22

Address: Apt. 895 30151 Green Plain, Lake Mariela, RI 98141

Phone: +5992291857476

Job: Legal Officer

Hobby: LARPing, role-playing games, Slacklining, Reading, Inline skating, Brazilian jiu-jitsu, Dance

Introduction: My name is Aracelis Kilback, I am a nice, gentle, agreeable, joyous, attractive, combative, gifted person who loves writing and wants to share my knowledge and understanding with you.