Zara  Bryant

Zara Bryant

1626376020

Hello, Django | Beginner's Series to: Django

It wouldn’t be an official programming video series if we didn’t do “Hello, world!” We won’t go against tradition, and walkthrough the classic demo, World. We will also see how the different files interact, and how to create our first route in Django to route user requests to our code.

Useful Links:

#django

What is GEEK

Buddha Community

Hello, Django | Beginner's Series to: Django

Variable de Impresión de Python

Python es un lenguaje versátil y flexible; a menudo hay más de una forma de lograr algo.

En este tutorial, verá algunas de las formas en que puede imprimir una cadena y una variable juntas.

¡Empecemos!

Cómo usar la print()función en Python

Para imprimir cualquier cosa en Python, se utiliza la print()función - que es la printpalabra clave seguida de un conjunto de apertura y cierre de paréntesis, ().

#how to print a string
print("Hello world")

#how to print an integer
print(7)

#how to print a variable 
#to just print the variable on its own include only the name of it

fave_language = "Python"
print(fave_language)

#output

#Hello world
#7
#Python

Si omite los paréntesis, obtendrá un error:

print "hello world"

#output after running the code:
#File "/Users/dionysialemonaki/python_articles/demo.py", line 1
#    print "hello world"
#    ^^^^^^^^^^^^^^^^^^^
#SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?

Si escribe su código Python en Visual Studio Code, con la extensión Python , también obtendrá un subrayado y una pista que indican que algo no está del todo bien:

Captura de pantalla-2021-12-07-a-3.08.14-PM

Como se mencionó anteriormente, la declaración de impresión se utiliza para generar todo tipo de información. Esto incluye datos textuales y numéricos, variables y otros tipos de datos.

También puede imprimir texto (o cadenas) combinado con variables, todo en una declaración.

Verá algunas de las diferentes formas de hacer esto en las secciones siguientes.

Cómo imprimir una variable y una cadena en Python usando la concatenación

Concatenar, según el diccionario, significa enlazar (cosas) juntas en una cadena o serie.

Esto se hace mediante la adición de varias cosas (en este caso la programación - se añaden datos), junto con otros, utilizando el operador de suma Python, +.

Tenga en cuenta que la concatenación solo se usa para cadenas, por lo que si la variable que desea concatenar con el resto de las cadenas es de un tipo de datos entero, tendrá que convertirla en una cadena con la str()función.

En el siguiente ejemplo, quiero imprimir el valor de una variable junto con algún otro texto.

Agrego las cadenas entre comillas dobles y el nombre de la variable sin rodearlo, usando el operador de suma para encadenarlos todos juntos:

fave_language = "Python"

print("I like coding in " + fave_language + " the most")

#output
#I like coding in Python the most

Con la concatenación de cadenas, debe agregar espacios usted mismo, por lo que si en el ejemplo anterior no hubiera incluido ningún espacio entre las comillas, la salida se vería así:

fave_language = "Python"

print("I like coding in" + fave_language + "the most")

#output
#I like coding inPythonthe most

Incluso puede agregar los espacios por separado:

fave_language = "Python"

print("I like coding in" + " " + fave_language + " "  + "the most")

#output
#I like coding in Python the most

Esta no es la forma más preferida de imprimir cadenas y variables, ya que puede ser propensa a errores y consumir mucho tiempo.

Cómo imprimir una variable y una cadena en Python separando cada una con una coma

Puede imprimir texto junto a una variable, separados por comas, en una declaración de impresión.

first_name = "John"

print("Hello",first_name)

#output
#Hello John

En el ejemplo anterior, primero incluí un texto que quería imprimir entre comillas dobles; en este caso, el texto era la cadena Hello.

Después de las comillas de cierre, agregué una coma que separa ese fragmento de texto del valor contenido en el nombre de la variable ( first_nameen este caso) que luego incluí.

Podría haber agregado más texto siguiendo la variable, así:

first_name = "John"

print("Hello",first_name,"good to see you")

#output
#Hello John good to see you

Este método también funciona con más de una variable:

first_name = "John"
last_name = "Doe"

print("Hello",first_name,last_name,"good to see you")

#output
Hello John Doe good to see you

Asegúrate de separar todo con una coma.

Entonces, separa el texto de las variables con una coma, pero también las variables de otras variables, como se muestra arriba.

Si no se hubiera agregado la coma entre first_namey last_name, el código habría arrojado un error:

first_name = "John"
last_name = "Doe"

print("Hello",first_name last_name,"good to see you")

#output
#File "/Users/dionysialemonaki/python_articles/demo.py", line 4
#    print("Hello",first_name last_name,"good to see you")
#                 ^^^^^^^^^^^^^^^^^^^^
#SyntaxError: invalid syntax. Perhaps you forgot a comma?

Como puede ver, los mensajes de error de Python son extremadamente útiles y facilitan un poco el proceso de depuración :)

Cómo imprimir una variable y una cadena en Python usando formato de cadena

Utiliza el formato de cadena al incluir un conjunto de llaves de apertura y cierre {}, en el lugar donde desea agregar el valor de una variable.

first_name = "John"

print("Hello {}, hope you're well!")

En este ejemplo hay una variable, first_name.

Dentro de la declaración impresa hay un conjunto de comillas dobles de apertura y cierre con el texto que debe imprimirse.

Dentro de eso, agregué un conjunto de llaves en el lugar donde quiero agregar el valor de la variable first_name.

Si intento ejecutar este código, tendrá el siguiente resultado:

#output
#Hello {}, hope you're well!

¡En realidad, no imprime el valor de first_name!

Para imprimirlo, necesito agregar el .format()método de cadena al final de la cadena, que es inmediatamente después de las comillas de cierre:

first_name = "John"

print("Hello {}, hope you're well!".format(first_name))

#output
#Hello John, hope you're well!

Cuando hay más de una variable, usa tantas llaves como la cantidad de variables que desee imprimir:

first_name = "John"
last_name = "Doe"

print("Hello {} {}, hope you're well!")

En este ejemplo, he creado dos variables y quiero imprimir ambas, una después de la otra, así que agregué dos juegos de llaves en el lugar donde quiero que se sustituyan las variables.

Ahora, cuando se trata del .format()método, importa el orden en el que coloque los nombres de las variables.

Entonces, el valor del nombre de la variable que se agregará primero en el método estará en el lugar de la primera llave, el valor del nombre de la variable que se agregará en segundo lugar estará en el lugar de la segunda llave, y pronto.

Asegúrese de separar los nombres de las variables con comas dentro del método:

first_name = "John"
last_name = "Doe"

print("Hello {} {}, hope you're well!".format(first_name,last_name))

#output
#Hello John Doe, hope you're well!

Si hubiera invertido el orden de los nombres dentro del método, la salida se vería diferente:

first_name = "John"
last_name = "Doe"

print("Hello {} {}, hope you're well!".format(last_name,first_name))

#output
#Hello Doe John, hope you're well!

Cómo imprimir una variable y una cadena en Python usando f-strings

f-strings son una forma mejor, más legible y concisa de lograr el formato de cadena en comparación con el método que vimos en la sección anterior.

La sintaxis es más sencilla y requiere menos trabajo manual.

La sintaxis general para crear un se f-stringve así:

print(f"I want this text printed to the console!")

#output
#I want this text printed to the console!

Primero incluye el carácter fantes de las comillas de apertura y cierre, dentro de la print()función.

Para imprimir una variable con una cadena en una línea, vuelva a incluir el carácter fen el mismo lugar, justo antes de las comillas.

Luego agrega el texto que desea dentro de las comillas, y en el lugar donde desea agregar el valor de una variable, agrega un conjunto de llaves con el nombre de la variable dentro de ellas:

first_name = "John"

print(f"Hello, {first_name}!")

#output
#Hello, John!

Para imprimir más de una variable, agrega otro conjunto de llaves con el nombre de la segunda variable:

first_name = "John"
last_name = "Doe"

print(f"Hello, {first_name} {last_name}!")

#output
#Hello, John Doe!

El orden en que coloque los nombres de las variables es importante, así que asegúrese de agregarlos de acuerdo con la salida que desee.

Si hubiera invertido el orden de los nombres, obtendría el siguiente resultado:

first_name = "John"
last_name = "Doe"

print(f"Hello, {last_name} {first_name}!")

#output
#Hello, Doe John!

Conclusión

¡Gracias por leer y llegar hasta el final! Ahora conoce algunas formas diferentes de imprimir cadenas y variables juntas en una línea en Python.

Si desea obtener más información sobre Python, consulte la Certificación Python de freeCodeCamp .

Es adecuado para principiantes, ya que comienza desde los fundamentos y se construye gradualmente hacia conceptos más avanzados. También podrás construir cinco proyectos y poner en práctica todos los nuevos conocimientos que adquieras.

¡Feliz codificación!

https://www.freecodecamp.org/news/python-print-variable-how-to-print-a-string-and-variable/

#python 

Ahebwe  Oscar

Ahebwe Oscar

1620177818

Django admin full Customization step by step

Welcome to my blog , hey everyone in this article you learn how to customize the Django app and view in the article you will know how to register  and unregister  models from the admin view how to add filtering how to add a custom input field, and a button that triggers an action on all objects and even how to change the look of your app and page using the Django suit package let’s get started.

Database

Custom Titles of Django Admin

Exclude in Django Admin

Fields in Django Admin

#django #create super user django #customize django admin dashboard #django admin #django admin custom field display #django admin customization #django admin full customization #django admin interface #django admin register all models #django customization

Ahebwe  Oscar

Ahebwe Oscar

1620185280

How model queries work in Django

How model queries work in Django

Welcome to my blog, hey everyone in this article we are going to be working with queries in Django so for any web app that you build your going to want to write a query so you can retrieve information from your database so in this article I’ll be showing you all the different ways that you can write queries and it should cover about 90% of the cases that you’ll have when you’re writing your code the other 10% depend on your specific use case you may have to get more complicated but for the most part what I cover in this article should be able to help you so let’s start with the model that I have I’ve already created it.

**Read More : **How to make Chatbot in Python.

Read More : Django Admin Full Customization step by step

let’s just get into this diagram that I made so in here:

django queries aboutDescribe each parameter in Django querset

we’re making a simple query for the myModel table so we want to pull out all the information in the database so we have this variable which is gonna hold a return value and we have our myModel models so this is simply the myModel model name so whatever you named your model just make sure you specify that and we’re gonna access the objects attribute once we get that object’s attribute we can simply use the all method and this will return all the information in the database so we’re gonna start with all and then we will go into getting single items filtering that data and go to our command prompt.

Here and we’ll actually start making our queries from here to do this let’s just go ahead and run** Python manage.py shell** and I am in my project file so make sure you’re in there when you start and what this does is it gives us an interactive shell to actually start working with our data so this is a lot like the Python shell but because we did manage.py it allows us to do things a Django way and actually query our database now open up the command prompt and let’s go ahead and start making our first queries.

#django #django model queries #django orm #django queries #django query #model django query #model query #query with django

Sival Alethea

Sival Alethea

1624378020

Python Django Web Framework - Full Course for Beginners. DO NOT MISS!!!

Learn the Python Django framework with this free full course. Django is an extremely popular and fully featured server-side web framework, written in Python. Django allows you to quickly create web apps.
⭐️Course Contents ⭐️
⌨️ (0:00:00) 1 - Welcome
⌨️ (0:01:14) 2 - Installing to Get Started
⌨️ (0:05:02) 3 - Setup your Virtual Environment for Django
⌨️ (0:14:39) 4 - Create a Blank Django Project
⌨️ (0:18:54) 5 - Setup Your Code Text Editor
⌨️ (0:22:27) 6 - Settings
⌨️ (0:29:58) 7 - Built-In Components
⌨️ (0:33:57) 8 - Your First App Component
⌨️ (0:42:34) 9 - Create Product Objects in the Python Shell
⌨️ (0:46:18) 10 - New Model Fields
⌨️ (0:52:52) 11 - Change a Model
⌨️ (0:59:27) 12 - Default Homepage to Custom Homepage
⌨️ (1:04:48) 13 - URL Routing and Requests
⌨️ (1:10:23) 14 - Django Templates
⌨️ (1:16:50) 15 - Django Templating Engine Basics
⌨️ (1:24:00) 16 - Include Template Tag
⌨️ (1:26:49) 17 - Rendering Context in a Template
⌨️ (1:33:21) 18 - For Loop in a Template
⌨️ (1:37:01) 19 - Using Conditions in a Template
⌨️ (1:42:17) 20 - Template Tags and Filters
⌨️ (1:48:59) 21 - Render Data from the Database with a Model
⌨️ (1:59:55) 22 - How Django Templates Load with Apps
⌨️ (2:06:50) 23 - Django Model Forms
⌨️ (2:14:16) 24 - Raw HTML Form
⌨️ (2:25:33) 25 - Pure Django Form
⌨️ (2:35:30) 26 - Form Widgets
⌨️ (2:41:29) 27 - Form Validation Methods
⌨️ (2:48:59) 28 - Initial Values for Forms
⌨️ (2:51:42) 29 - Dynamic URL Routing
⌨️ (2:54:26) 30 - Handle DoesNotExist
⌨️ (2:56:24) 31 - Delete and Confirm
⌨️ (2:58:24) 32 - View of a List of Database Objects
⌨️ (3:00:00) 33 - Dynamic Linking of URLs
⌨️ (3:01:17) 34 - Django URLs Reverse
⌨️ (3:03:10) 35 - In App URLs and Namespacing
⌨️ (3:07:35) 36 - Class Based Views - ListView
⌨️ (3:10:45) 37 - Class Based Views - DetailView
⌨️ (3:15:38) 38 - Class Based Views - CreateView and UpdateView
⌨️ (3:21:23) 39 - Class Based Views - DeleteView
⌨️ (3:24:02) 40 - Function Based View to Class Based View
⌨️ (3:27:15) 41 - Raw Detail Class Based View
⌨️ (3:30:31) 42 - Raw List Class Based View
⌨️ (3:33:32) 43 - Raw Create Class Based View
⌨️ (3:26:03) 44 - Form Validation on a Post Method
⌨️ (3:37:58) 45 - Raw Update Class Based View
⌨️ (3:41:13) 46 - Raw Delete Class Based View
⌨️ (3:42:17) 47 - Custom Mixin for Class Based Views

📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=F5mRW0jo-U4&list=PLWKjhJtqVAbnqBxcdjVGgT3uVR10bzTEB&index=6
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#python #django #python django web framework #beginners #full course #python django web framework - full course for beginners

Ananya Gupta

Ananya Gupta

1597123834

Main Pros and Cons of Django As A Web Framework for Python Developers

Django depicts itself as “the web system for fussbudgets with cutoff times”. It was intended to help Python engineers take applications from idea to consummation as fast as could be expected under the circumstances.

It permits fast turn of events on the off chance that you need to make a CRUD application with batteries included. With Django, you won’t need to rehash an already solved problem. It just works and lets you center around your business rationale and making something clients can utilize.

Pros of Django

“Batteries included” theory

The standard behind batteries-included methods normal usefulness for building web applications accompanies the system, not as isolated libraries.

Django incorporates much usefulness you can use to deal with normal web advancement undertakings. Here are some significant level functionalities that Django gives you, which else you need to stay together if you somehow happened to utilize a small scale structure:

ORM

Database relocations

Client validation

Administrator board

Structures

Normalized structure

Django as a system proposes the right structure of an undertaking. That structure helps designers in making sense of how and where to execute any new component.

With a generally acknowledged venture structure that is like numerous tasks, it is a lot simpler to discover online good arrangements or approach the network for help. There are numerous energetic Python designers who will assist you with comprehending any issue you may experience.

Django applications

Django applications (or applications for short) permit designers to separate a task into numerous applications. An application is whatever is introduced by putting in settings.INSTALLED_APPS. This makes it simpler for engineers to add usefulness to the web application by coordinating outer Django applications into the venture.

There are many reusable modules and applications to accelerate your turn of events learn through Online Django Class and Check the Django website.

Secure of course

Django gives great security assurance out of the crate and incorporates avoidance components for basic assaults like SQL Injection (XSS) and Cross-site Request Forgery (CSRF). You can discover more subtleties in the official security diagram control.

REST structure for building APIs

Django REST Framework, commonly condensed “DRF”, is a Python library for building APIs. It has secluded and adaptable engineering that functions admirably for both straightforward and complex web APIs.

DRF gives a lot of verification and authorization strategies out of the case. It is an adaptable, full-included library with measured and adjustable engineering. It accompanies nonexclusive classes for CRUD tasks and an implicit API program for testing API endpoints.

GraphQL structure for building APIs

Huge REST APIs regularly require a lot of solicitations to various endpoints to recover every single required datum. GraphQL it’s a question language that permits us to share related information in a lot simpler design. For a prologue to GraphQL and an outline of its ideas, if it’s not too much trouble allude to the authority GraphQL documentation.

Graphene-Django gives reflections that make it simple to add GraphQL usefulness to your Django venture. Ordinary Django models, structures, validation, consent arrangements, and different functionalities can be reused to manufacture GraphQL blueprint. It additionally gives an implicit API program for testing API endpoints.

Cons of Django

Django ORM

Django ORM, made before SQLAlchemy existed, is currently much sub-par compared to SQLAlchemy. It depends on the Active Record design which is more regrettable than the Unit of Work design embraced by SQLAlchemy. This implies, in Django, models can “spare” themselves and exchanges are off as a matter of course, they are a bit of hindsight. Peruse more in Why I kind of aversion Django.

Django advances course popularity increses day by day:

Django is huge and is viewed as strong bit of programming. This permits the network to create several reusable modules and applications yet has additionally restricted the speed of advancement of the Django. On head of that Django needs to keep up in reverse similarity, so it advances gradually.

Rundown - Should I use Django as a Python designer?

While Django ORM isn’t as adaptable as SQLAlchemy and the enormous environment of reusable modules and applications hinders structure advancement - plainly Django ought to be the best option web system for Python engineers.

Elective, light systems, similar to Flask, while offering a retreat from Django huge biological system and designs, in the long haul can require substantially more additional libraries and usefulness, in the end making many experienced Python engineers winding up wishing they’d began with Django.

Django undertaking’s security and network have become enormously over the previous decade since the system’s creation. Official documentation and instructional exercises are probably the best anyplace in programming advancement. With each delivery, Django keeps on including huge new usefulness.

#django online training #django online course #online django course #django course #django training #django certification course