fabiochiu/medium-articles huggingface dataset:
Reverse relationship in Django
By: Allwin Raju
Tags: Django Child Relationship, Django, Django Parent Child, Django Parent From Child

This blog post teaches you about the relationship between the child and parent models and vice versa. Let us consider the following School and Student models for example.

Photo by Aditya Romansa on Unsplash

The student model will have the student name and the school model will have the school name alone for simplicity.

This is how our models look like.

from django.db import models





class School(models.Model):

name = models.CharField(max_length=100)



def __str__(self):

return self.name





class Student(models.Model):

name = models.CharField(max_length=100)

school = models.ForeignKey(School, on_delete=models.CASCADE, related_name='student')



def __str__(self):

return self.name

Direct relationship

In the above Student model, the school field has a foreign key relationship with the school model.

This is an example of a direct relationship. If we wish to get the school name from a student object we can simply do the following.

>>> from student.models import Student

>>> student = Student.objects.all().first()

>>> student

<Student: John>

>>> student.school.name

'Stanford'

Or if you want to query all the students whose school name is ‘Stanford’ we can simply do the following.

>>> students = Student.objects.filter(school__name='Stanford')

>>> students

<QuerySet [<Student: John>]>

This is straightforward and simple, right? We are accessing the parent object from the child object. What if we want to do the opposite of this? Let us say we would like to query the parent objects based on applying some conditions to the child object.

Reverse relationship

If we look at the models, it gives us a feeling that only child objects are mapped to the parent objects and not the other way round right?

This is where the “related_name” argument comes for the rescue. This will act as a field in the model while querying parent objects based on the child models.

Let us say I need to query all the schools where a student named ‘John’ is present. Then I can do the following.

>>> from student.models import Student, School

>>> School.objects.filter(student__name='John')

<QuerySet [<School: Stanford>]>

I have a student named ‘John’ in ‘Standford’ school record. Let me add one more ‘John’ to some other school and query again. Now two schools will be returned.

>>> from student.models import School

>>> School.objects.filter(student__name='John')

<QuerySet [<School: Stanford>, <School: Harvard>]>

This is my student table records.

student table record

We have successfully filtered parent values from the child values using reverse relationship with “related_name” attribute.

Conclusion

Hope this article is helpful. Follow me for more articles on Django and Python. Happy coding!
Top Five Books that can be used for learning Django from Scratch :
Tags: Médium, Django, Django Rest Framework

Top Five Books that can be used for learning Django from Scratch :

Django is one among the foremost popular Python frameworks for web development. Django provides a lot of libraries and solutions for common tasks, which makes it easier and faster for developers to create even complex web applications. Learning

Django is important if you’re into web development and Python programming. Books and learning go hand in hand, and this text will tell you about 5 best Django books for all levels of learners. But before that, let’s do a fast recap of what Django is.

1. Django Design Patterns and Best Practices:

Though a design patterns book, it covers a good amount of basics about Django starting with why Django came into existence. The author discusses at length how simple and sophisticated problems that are quite common , especially once we want faster development, are often solved by making simple design changes. Knowing about various patterns can greatly reduce the coding time and enhance code performance.

2. Beginning Django E-Commerce :

This book is for beginners, who may or might not have a Django background. However, you ought to have a good understanding of HTML, CSS, XML, SQL aside from Python. Some topics that this book covers (like deployment, testing, performance tuning) aren’t covered adequately in other books. it’s a step by step guide to making an e-comm website, however, the author doesn’t spoon-feed you at the most places.

3. Lightweight Django 1st Edition :

The author takes a posh project, breaks it into smaller components and goes on to elucidate each component, making it easy for readers to know the low-level details also because the overall picture. Every line of code is explained well, there’s a reasoning for everything that the author does — the detailing is simply amazing.

4.Practical Django 2 and Channels 2 :

The author covers an excellent amount of data and makes some boring topics interesting through examples. The author seems to understand a developer’s mindset perfectly — while reading if you seem to possess a doubt, it’ll be cleared because the next thing within the book! The author touches upon all the domains — e-commerce, finance, banking by giving use cases from each of those enabling developers to use the techniques and guidance in their projects.

5.Django Unleashed :

The book may be a detailed guide and starts with scratch to create applications in Django. It explains various ways of solving an equivalent problem then explains which one is best too. The author takes it slowly from basics to complex topics and though some advanced topics could also be a touch difficult to follow initially, once you practice them, you’ll appreciate the trouble the author has put to elucidate them.
How to Schedule Django custom Commands on AWS EC-2 Instance?
By: Fauzan Khan
Tags: Django, Ec2 Instance, AWS, Crontab, Python

Step -1

First, you need to write a .cron file

Step-2

Write your script in .cron file.

MyScript.cron

* * * * * /home/ubuntu/kuzo1/venv/bin/python3 /home/ubuntu/Myproject/manage.py transfer_funds >> /home/ubuntu/Myproject/cron.log 2>&1

Where * * * * * means that the script will be run at every minute. you can change according to need (https://crontab.guru/#*_*_*_*_*).

Where /home/ubuntu/kuzo1/venv/bin/python3 is python virtual environment path.

Where /home/ubuntu/kuzo1/manage.py transfer_funds is Django custom command path

&

/home/ubuntu/kuzo1/cron.log 2>&1 is a log file where you can check your running cron log
Top Three Platform to learn Coding in this Tech World ?
Tags: Coding, Django

Top Three Platform to learn Coding in this Tech World ?

1 . CodeChef : { https://www.codechef.com/ }

The CodeChef is that the only platform to find out the simplest technical skills supported various approaches in programming not only this with many continuous coding contests is there to urge an edge over the coding.CodeChef is an academic initiative by Directi, an Indian software company. it’s a worldwide programming community that fosters learning and friendly competition, built on top of the world’s largest competitive programming platform. we’ve also built an outsized community of problem curators.

2. GeeksforGeeks: { https://www.geeksforgeeks.org/ }

The GeeksforGeeks is the only website which contains all the data not only related to the coding environment but also the various mode of tracking the preparation in the various tech world like preparations for the tech companies in-depth way by providing the various realtime coding examples asked in tech companies. The GeekforGeek not only stops on this provide the various opportunity to dig in-depth for the topic related to programming.

3.CodeAcademy : { https://www.codecademy.com/ }

Codecademy is an education company. But not one within the way you would possibly think. We’re committed to putting together the simplest learning experience inside and out, making Codecademy the simplest place for our team to find out, teach, and make the web learning experience of the longer term

Education is old. the present public establishment within the US dates back to the 19th century and wasn’t designed to scale the way it’s. many companies are working to “disrupt” education by changing the way things add the classroom and by bringing the classroom online.
Follow & Unfollow System in Django
Tags: Medium, Django, Python, First Post

Do you use Social Media like Instagram, Twitter, Facebook or Dev. The common thing is all of have Follow/Unfollow System.

Here In this post, You can create your own follow/unfollow system using Python Django. It is very simple to make.

Click this DEV link and You will reach my DEV profile where I have uploaded Source code of this Project.
Django file storage with Cloudinary.
By: Arghya Mondal
Tags: Django Storages, Cloudinary, Django, Python

Enough talk let's code! First, go to https://cloudinary.com/users/register/free to get a free account. I recommend creating a new google account for managing business before you do that (although that’s completely optional). Then You will be taken to the console.

Cloudinary Dashboard

Now that's all you would need for your Cloudinary dashboard. Now you need to access the Cloudinary storage using your Django app. Luckily for that, we have a python library.

Use the command: pip install django-cloudinary-storage in your terminal.

Also since we are uploading images we need to have the pillow library (pip install Pillow)

Next, add the libraries to your installed apps as shown in the below picture. Make sure that cloudinary_storage is before django.contrib.staticfiles as shown below.
How to Schedule Django Commands on AWS Elastic Beanstalk
By: Sahar Mor
Tags: Programming, Django, DevOps, AWS, Python

How to Schedule Django Commands on AWS Elastic Beanstalk

Photo by the author.

Recently, I was looking to run a script once an hour that also required my Django app context. Though I did find a couple of online guides, they were either outdated or not comprehensive and aligned with the recent changes in AWS Elastic Beanstalk (EBS).

EBS allows us to run web apps such as Django in a seamless and managed way. That also means we shouldn’t set up any local cron jobs on our current, randomly assigned EC2 instances. Instead, we do it within our EBS environment.

In this guide, I’ll outline how to define your Django command, create an EBS config file, and deploy and test your newly created scheduled script.
Benefits of to know full stack web development in today’s IT Market.
Tags: Web Development, HTML, Django, Full Stack, Python

DridhOn e-Learning provides you best online Live instructor led training on 400+ IT & Non IT courses with 24/7 Customer support & Placement Assistance.
How to fix Django’s HTTPS redirects in nginx
By: Antonis Christofides
Tags: Django, Nginx

You deploy with nginx and Gunicorn and your site uses HTTPS. If Django occasionally returns HttpResponseRedirect or similar, you may find that the redirect sends you back to HTTP. Here’s how to fix it.

In the nginx configuration (inside the location block), specify this:

proxy_redirect off;

proxy_set_header X-Forwarded-Proto $scheme;

The proxy_redirect off statement tells nginx that, if the backend returns a redirect, it should leave it as is. By default, nginx assumes the backend is stupid and tries to fix the response; if, for example, the backend returns a redirect that says “redirect to http://localhost:8000/somewhere”, nginx replaces it with something similar to “http://yourowndomain.com/somewhere”. But Django isn’t stupid (or it can be configured to not be stupid), and it will typically return a relative URL. If nginx attempts to “fix” the relative URL, it will likely break things. Instead, we use proxy_redirect off so that nginx merely passes the redirection as is.

The second line is only necessary if your Django project ever uses request.is_secure() or similar. It’s a good idea to have it because even if it doesn’t today it will tomorrow, and it does no harm. Django does not know whether the request has been made through HTTPS or plain HTTP; nginx knows that, but the request it subsequently makes to the Django backend is always plain HTTP. We tell nginx to pass this information with the X-Forwarded-Proto HTTP header, so that related Django functionality such as request.is_secure() works properly. You will also need to set SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') in your settings.py .

This is a republication of an old article first published in my Django Deployment site.
Django Custom Language and Time Zone
By: Adi Ramadhan
Tags: Language, Django, Timezone

Simple customization for language and timezone in django admin. By default django language is English and UTC Timezone. We can change to another language and timezone. Here’s the example, Language Bahasa Indonesia, timezone: GMT+7 (Jakarta’s Time). Official docs for Django internationalization and localization here. Focus in timezone, django use pytz library, and we can see official pytz doc here.

Default and Bahasa Indonesia Django Homepage

Step 1: Preparation, Create Django Project, Initial Migration

create virtualenv: virtualenv venv

start virtualenv: venv/Scripts/activate

install Django in virtualenv: pip install django==3.0

Create Django: django-admin startproject myproject

Go to myproject folder: cd myproject

Initial Migration: python manage.py migrate

Step 2: Create Superuser

Create superuser: python manage.py createsuperuser

Type username, email password and retype password

Step 3: Set Language and Time Zone in myproject/setting.py

Update LANGUAGE_CODE and TIME_ZONE setting.py

... LANGUAGE_CODE='id' TIME_ZONE = 'Asia/Jakarta' ...

Note: list of language_code here. Time zone here.

Step 4: Run Server and Testing

Run Server: python manage.py runserver

Access: http://127.0.0.1:8000

Homepage

Admin Login Page
Setup Pycharm for Django project
By: Grassroot Engineer
Tags: Pycharm, Django

Electronics engineer who is interested in CODING and believe in EFFORT. — formerly http://grassrootengineer.medium.com
How to Deploy a Django Project to a Server in China?
Tags: Django Admin, Django Framework, Django, China, 21yunbox

What is Django?

Django’s Official Website

Django is an open source web application framework developed based on Python. The Django framework not only provides a complete code directory structure, but also uses the structure model, view, and template. This makes the code easy to standardize during the development process. Among them, Django Admin provides an out-of-the-box back-end management system and is the “Go-To” by many Python developers and startups.

21YunBox provides a very simple Django deployment method. You can deploy on the 21YunBox in the Python environment.

Register as a 21YunBox member Create a PostgreSQL database Fork Django example Create a Cloud Service on the 21YunBox, and allow the 21YunBox to access your code base Configure the following settings

Environment

PYTHON 3.7

Build command:

./build.sh

Start command:

gunicorn hello.wsgi:application

Click Advanced Configuration to configure environment variables:

For more Django-related configurations, please refer to Official Document. In this example, DJANGO_DEBUG=True is a demonstration and example only. You can set DJANGO_DEBUG to False in the environment variable when it goes live.

Once the build is complete, use the remote connection of the 21YunBox to create a Django administrator account

It’s that easy! When the build is completed, your application will be accessible in the subdomain of 21YunBox.

If the description of the above text is not clear, you can refer to the following actual example video: How to Deploy Django Application to Server

Why Choose 21YunBox?

21YunBox is a Cloud Service platform based out of Beijing. Our services enable your team to be more effective in leveraging the growing opportunity within China by hosting your sites at blazing speeds with an operational and maintenance free solution. We offer an easy and budget friendly, end-to-end web platform deployment service for all applications from small teams to large enterprises using a low-code solution. We also offer full support in obtaining your ICP license. This allows you to do legally do business inside of Mainland China.

To learn about the differences between 21YunBox and these foreign (outside of China) cloud service platforms? You can refer to:
Importing CSV file into Django Database
By: Aditya Khandelwal
Tags: Model, Database, Django, Csv File, Import Excel

This is a 5 steps guide to Import your data from a csv file to your django database using Django management Command.

A CSV is a comma-separated values file, which allows data to be saved in a tabular format.

Applications can register their own actions with manage.py using custom django-admin commands. For example, you might want to add a manage.py action for a Django app that you’re distributing. In this article, we will import the data of children.csv to the children model using the custom django-admin commands, such as:-

python manage.py load_child_data

children.csv:

children.csv

Step 1- Make a Django Project named as csv_import.

django-admin startproject csv_import

Step 2- Make a Django app named as children.

python manage.py startapp children

Step 3- Now, we will make a model to store the data of the csv file and register that model in Django admin interface.

models.py:-

from django.db import models class children(models.Model): name=models.CharField(max_length=100)

SEX_CHOICES=[('M','Male'),('F','Female')]

sex = models.CharField(max_length=1, choices=SEX_CHOICES)

age=models.IntegerField(null=True)

def __str__(self):

return self.name

admin.py:-

from django.contrib import admin from .models import children @admin.register(children) class childrenAdmin(admin.ModelAdmin): list_display=['name','sex','age']

Note: Make sure you have added our app in installed apps in settings.py, migrated all the migrations and created a superuser to see the data in the database.

Step 4:- Now, we will add a management/commands directory to the application. Django will register a manage.py command for each Python module in that directory whose name doesn’t begin with an underscore. For example:

children/

__init__.py

models.py

management/

commands/

_private.py

load_child_data.py

tests.py

views.py

load_child_data.py:-

load_child_data.py

Step 5:- Finally, paste the CSV file i.e., children.csv in the same folder as manage.py and type in the command prompt or shell:

python manage.py load_child_data

Run the server.

Wooohoooo! Check the database to see the loaded data from the CSV file into your django model.

In case you still have any doubts you are welcome to refer to my github repository for the same by the following link:-

Hope this helps!
Which components should I use in production?
By: Antonis Christofides
Tags: Django

This is the last in a series of posts about whether you should choose Ubuntu or Windows, Gunicorn or uWSGI, MySQL or PostgreSQL, and Apache or nginx. I bring it all together. The image illustrates the components I propose for a start.

My way of thinking is reflected in my seemingly unorthodox proposal of using SQLite on production. We should start with the simplest and easiest (and therefore most economical) collection of components possible, and only replace these components with something else if needed. Here are some examples of reasons for which you would want to replace a component:

Is your web site going to have many concurrent write requests? Or is the database going to have 100k or more records and/or do complicated queries? Throw out SQLite and use PostgreSQL.

Update: It can be risky to choose SQLite, as it might lead to a nightmarish migration later. Read “Which database should I use in production?” for more information.​

Do you need content negotiation? Do you need to run WordPress on the same server? Use Apache. (You can also run WordPress with nginx, but it’s harder, and it’s not justified just because nginx is more fashionable.)

Are you affected by a Windows-only company policy and are so far unable to get the company to reconsider? Use Windows, Apache, and mod_wsgi.

Start simple, and only replace with something else if it’s really needed.

Related posts:

Also related:
How to run Django tests in PyCharm?
Tags: Pycharm, Django, Django Tests, Django Rest Framework

How to run Django tests in PyCharm?

PyCharm has facilitated Django (and Django Rest Framework) tests by:

But if you click it, you will got some errors. That is because you haven’t configured it well.

First, we need to configure the Django tests template, click Run -> Edit configurations , them click the `wrench` icon, like this:

Then, we need to set the `Custom settings` add all the `Environment variables`.

That is all.
Facebook Messenger Webhooks: The Callback URL or Verify Token couldn’t be validated. Please verify the provided information or try again later.
By: Emre Bayram
Tags: Facebook, Webhooks, Django, Error

Facebook Messenger Webhooks: The Callback URL or Verify Token couldn’t be validated. Please verify the provided information or try again later. Emre Bayram ·Dec 16, 2020

This error message made me crazy today and cost me 15 minutes.

So writing here the potential mistake you are making so maybe you can save 10 minutes if you have found this page in 5 minutes:)

I was using Django REST Framework as my messenger backend.

And my response was basically:

return Response(request.GET.get('hub.challenge'),status=status.HTTP_200_OK)

which seems perfectly aligned with the documentation. The problem is you need to return a plain HTTP response not something that would wrap the “hub.challenge” parameter.

So here is how you need to fix it:
Which WSGI server should I use?
By: Antonis Christofides
Tags: Wsgi, Mod Wsgi, Uwsgi, Django, Gunicorn

Gunicorn, uWSGI, or mod_wsgi? What the heck is a WSGI server? Why do I need one? Which one should I choose?

Short answer: Use Gunicorn, unless you are deploying on Windows, in which case use mod_wsgi.

Long answer:

As seen in the picture, the web browser talks to the web server, and the web server in turn talks to the WSGI server. The WSGI server doesn’t talk to your Django project, it imports your Django project. It does something like this:

from django_project.wsgi import application

application(args)

So, from the operating system’s point of view, your Django project becomes a part of the WSGI server; it is the same process. The way application() is called is standardized by the WSGI specification. The fact that the interface of this function is standardized is what permits you to choose between many different WSGI servers such as Gunicorn, uWSGI, or mod_wsgi, and why each of these can interact with many Python application frameworks like Django or Flask.

mod_wsgi is for Apache only, and I prefer to use a method that can be used with either Apache or nginx. This will make it easier to change the web server, should such a need arise. I also find Gunicorn easier to setup and maintain.

I used uWSGI for a couple of years and was overwhelmed by its features. Many of them duplicate features that already exist in Apache or nginx or other parts of the stack, and thus they are rarely needed. Its documentation is a bit chaotic. The developers themselves admit it: “We try to make our best to have good documentation but it is a hard work. Sorry for that.” I recall hitting problems week after week and spending hours to solve them each time.

Gunicorn, on the other hand, does exactly what you want and no more. It is simple and works fine. So I recommend it unless in your particular case there is a compelling reason to use one of the others.

uWSGI and Gunicorn don’t run in Windows, so if you are deploying on Windows use Apache + mod_wsgi.
Fantastic Bytes and How to Use Them
Tags: Python, Django, Python Flask, Python3

Bytes IO

String IO

WEBP IO

An example of rendering plots in memory with BytesIO

This is figure can directly be passed as a variable to Jinja/Jinja2 template engine and it’ll render it as webp.

return render_template('index.html', figure=figure)

Line 10 in WEBP IO decodes the stored image format in a way that is understood by the browsers. (Base 64 encoding/decoding)
Django Social Share Integration Steps
Tags: Django, Social Media

Django Social Share Integration Steps

The Django Social Share in the one of the unique Feature or library in django that make very effiecient for us to make the social media share links with very easier and unique without any trouble to handle the posting the website link post on the social platform , by single click we can easily share the post on any socail media platform .

Some of the platform , I will show how we can Integrate in our django website and make use of the very nice feature or the library to connect to social media and share our to all over the world by just one click .

Step 1 : We need to install below package to use the django-social-share.



pip install django-social-share

Step 2 : Once we Install this Package successfully we can use all the below templatags to share the content for :

Provides templatetags for:

Step 3 : Now , we are good to go to proceed further , Inside Django project open “ settings .py “ file and add the below line :

INSTALLED_APPS += [‘django_social_share’] or INSTALLED_APPS = [“django_social_share’ ]

Step 4 : Following are the simple tags that we can use now to proceed further .

{% add_pinterest_script %}

Step 5 : Usage of the each templatetags in details as below :

<text_to_post> may contain any valid Django Template code. Note that Facebook does not support this anymore.

<object_or_url> is optional (except Telegram). If you pass a django model instance, it will use its get_absolute_url method. Additionally, if you have django_bitly installed, it will use its shortUrl on Twitter.

<link_text> is also optional. It defines the text used for the a element. Defaults to ‘Post to Facebook’ and ‘Post to Twitter’.

<subject> may contain any valid Django Template code.

Step 6 : Below is the actual way we can use the template in our code as follows :

{% post_to_twitter_url <text_to_post> <object_or_url> %}

Will add a tweet_url variable to the context, containing the URL for the Twitter sharer popup.

{% post_to_facebook_url <object_or_url> %}

Will add a facebook_url variable to the context, containing the URL for the Facebook sharer popup.

{% post_to_gplus_url <object_or_url> %}

Will add a gplus_url variable to the context, containing the URL for the Google+ sharer popup.

{% send_email_url <subject> <text_to_post> <object_or_url> <link_text> %}

Will add a mailto_url variable to the context, containing the URL for the mailto anchor.

{% post_to_reddit_url <text> <object_or_url> %}

Will add a reddit_url variable to the context, containing the URL for the Reddit poster page.

{% post_to_telegram <text> <object_or_url> %}

Will add a telegram_url variable to the context, containing the URL for the Telegram sharer popup.

Step 7 : Now , Once we add all the social medial tempplate tags we can now simply replace the url by using the below , these command where ever you write in any template of the django website you will get that page link that you want to share on social media platform .

Command : {{ request. build_absolute_uri }}

Step 8 : Its looks like as follows :
A Basic Overview of Django, the Python Web Framework
By: Leo Falcone
Tags: Portal, Web Development, Django Framework, Django, Python

During this quarantine I’ve had a lot of free time...

I wanted to learn how to write a website the hard way, and do the coding myself (instead of using a template like Wix or Squarespace). After some hours of research, I came to what I learned is one of the most useful frameworks for a web developer to know, called Django.

Django is a python web framework that allows you to create an administrator view. It is most commonly used for websites that have forms (think about a login page where you fill out all of your information). The administrator creates a specific view, where they are able to see the results of the form submissions or perform actions like managing usernames/passwords.

Alternatively, when you create a website in Wix or a similar template, your page operates like a billboard where you (the “admin”) can only see the same page as clients visiting the site.

Django is not an easy or intuitive framework to learn. While I never found a complete guide, I eventually figured out my website using a combination of Stack Overflow, YouTube, and the available resources on Django website. You can view my final product at LeonardoFalcone.com. I should mention that getting the website up onto an internet server was an entirely different battle that I am not going to overview in the simplified steps below.

The steps below are not comprehensive and are just meant to give you the basics. If you want to write a website of your own, you should begin with the steps listed on https://www.djangoproject.com/

The process begins in your terminal, where you need to install Django and create a new project. Once Django is installed and the

project is created, you can then open it in your interpreter (I was using VS Code). When you open the interpreter, there will be files with templates that already have some code written for you.

The above are the .py files given when you open a new Django project.

You then create a separate file within this project which will include your HTML. This file will decide what your webpage is going to look like. For example, you will include any colors, text, and images in this HTML code.

Once you are finished, you tell the program to return your HTML through a file called “vews.py”. You can then see your website up and running in a test environment, which you will need to open through the terminal.

While there can be significantly more steps in between, that is the summary of writing a basic website in the program. There is an endless possibility of functions that your Django web program can perform. For example, the one I created includes an app that graphs the price and volume of stocks over a set timeframe.

Some well-known examples of apps written on the Django framework are YouTube, Instagram, Pinterest, and Spotify. It is an excellent skill to know for both large and small scale platforms. The best part about Django is that it is an open-source project; meaning that anybody is free to use, study, modify, and distribute the framework for any purpose.
Django ORM internals- Environment setup
By: Asit Mahato
Tags: Django Orm, Object Relational Mapping, Orm, Django, Python3

Django ORM internals- Environment setup

In this article, we will learn how Django ORM works. According to experts, If we would like to learn some new thing, the best way is, to read the code base of some existing implementation.

If you are working in some Python-based ORM & you are not looking into the Django codes then, either you are missing something or you are way above the normal developer like me.

I would like to make it clear at the beginning, it will not be about any web application development using the Django framework. I am learning how any ORM works & reading the Django code is the best place to start with. It will be a series of posts. It might help, If we are looking for a guide that will help to use the only ORM feature of Django.

Tools:

Since the intention is to know the internals of Django ORM, the first step towards it should be to have the source code from it’s development branch. As it is a nice practice to have a virtual environment for each of the projects, we will use conda to manage our virtual environments. We are not going into details about the conda installation process to make this post shorter. As the virtual environments help us to segregate the python development environments, in a similar way docker can help us with the other applications, so for the database application, we will use docker. And again we can follow some other resources from the internet to get us started with docker and docker composer. And finally, about the IDE, I am using the Pycharm community edition.

Setup :

So, we have talked about the tools that are being used, now let’s follow the steps to get us started as an ORM developer.

Create and activate the virtual environment

~$ conda create -n django-dev python=3.9

~$ conda activate django-dev

Clone the latest Django source code from Github



~$ cd django ~$ git clone https://github.com/django/django.git ~$ cd django

Install Django from the source

~$ python -m pip install . # make sure you are inside the django dir

Create a Project & App for the ORM experiments

~$ mkdir experiment && cd experiment

~$ django-admin startproject ormtest .

~$ python manage.py startapp modeltest

Modify the setting file to satisfy our requirement

By default, django will create a setting file that can be used by the web application. Since we will require the database connection part only, we will remove the other unrelated configs. The final setting file will look like the below one. Here I have attached the docker-composer file as well for reference purposes. And the docker container can be started by the below command.

~$ sudo docker-compose up # in the dir with compose.yml



Final Step

We are almost done with the setup. We can run a basic test code using the below sample. In the below sample it is assumed that we are having a model “Device” in the modeltest’s models file.
Django — Creating Model Forms. Model forms in Django are a seamless…
Tags: Python Programming, Coding, Web Development, Django, Python

Model forms in Django are a seamless way to create web-based forms with the ability to store data in the database.

Assuming your Django project is created and you have created an application folder (if not, see the documentation for the setup process), let’s get started creating a model form.

Firstly, we have created a simple model in models.py for a ‘client’ with 2 name fields. The ‘str’ function enables us to view the model outputs cleanly in the admin panel.

from django.db import models



class Client(models.Model):

first = models.CharField(max_length=50)

surname = models.CharField(max_length=50)



def __str__(self):

return f'{self.first}, {self.surname}'

Once saved and migrated, we will now create a forms.py file in our application directory (sits alongside models, views etc).

Here we will import forms, model form and the relevant model we have created (‘Client’). The class of ClientForm is created (ensure you keep congruency with the model name) where we define the model and the fields. In this case we will want both name fields (‘__all__’).

from django import forms

from django.forms import ModelForm

from .models import Client





class ClientForm(forms.ModelForm):

class Meta:

model = Client

fields = '__all__'

We’ll now head over to the views.py file and write the code that will process the data, save it and redirect us back to a home page. Ensure that ‘redirect’ is imported via django.shortcuts.

def client(request):

form = ClientForm From 'forms.py'



if request.method == 'POST':

form = ClientForm(request.POST)

if form.is_valid(): If completed:

form.save() Save the form

return redirect('/') Back To Home



context = {'form': form} Use in template

return render(request, 'client.html', context)

To render this out on a web-page, we’ll (1) write a url path in our application’s urls.py file:

path('client/', client, name='client'),

…and (2) create a ‘client.html’ file in a templates folder:

<h1> Client Data </h1>

<hr>



<form method="post">



{% csrf_token %} Required to process form

{{ form }} From our context variable



<input type="submit">



</form>

Our client URL (http://127.0.0.1:8000/client/) will now render and display the basic form below.

We can input data which will be saved (& viewed in the admin panel) and upon completion of the form will get redirected back to our home page.

For more information and if you get stuck, visit the official documentation on ModelForms here.
Top 5 Guides To Master Django In 2021
By: Moeed Rafique
Tags: Web Development, Django Framework, Django, Learning To Code, Python

Django is the best web development framework with its roots linked with Python. Its simple syntax and the opportunity it gives to its user is awesome.

WHY DJANGO IS BEST?

The most important reasons are following:

1. Simple Syntax

2. Pre built stuff such as its Admin Panel

3. High Scalability

4. Suitable for every Project

5. Highly Paid

6. Low learning Curve

7. High Security

8. Huge Community

And the list goes on and on ……

>If you want to learn and master your skills these are best open source resources on the internet.

For beginners the number one course is by Corey Schafer. In his playlist you will learn about many major concepts such as User Authentication, Authorization, Sending Emails, Pagination, Permissions, Creating Profiles using Django Signals.

Here is the link to playlist in which you will learn how to make a simple blog with Django.

> The second on the list is my favourite Dennis Ivy. In his playlist DJANGO CRASH COURSE you will be able to cover some concepts such as How to use filters, password resets. Most of concepts are linked with previous playlist but it will give you huge understanding. You will make a CONTENT MANAGMENT SYSTEM in this course.

>The third on the list is a playlist from John from Codemy.com. In his course you will learn how to create a complex blog with things such as comments, user restrictions, adding like buttons.

>If you had completed all of the courses here is bonus course in which rather than making traditional blog site you will learn all the basics and will be making a real world app. Yes you will be making a Craigslist app with Django using complex concepts such as web scraping etc. Its 8 hours long video so enjoy it.

>On the last we again have a video from Dennis in which you will be making your first personal portfolio website dynamically with Django. This video is 100 times better than a udemy course.
How To Build A Stack Class In Python
By: Ronald Abreu
Tags: Algorithms, Stack, Django, Data Structures, Python

How To Build A Stack Class In Python

Photo by Iva Rajović on Unsplash

In this article we will be building a stack class in Python.

Even if you are unfamiliar with stacks or Python classes, below is everything you need to know to follow along!

Stacks are collections of objects arranged in a straight line, they follow a linear data structure in which adding or removing to and from the stack can only happen at a single end of the collection, making these LIFO or last in first out data structures. Think dinner plates, or a stack of pancakes.

We will be using a class to represent a stack in order to see it in action. We will write methods like push and pop which will add and remove objects from our collection.

To add items to the top of the stack we use:

append()

To retrieve an Item from the top if the stack we use:

pop()

Both these operations happen on the right side end of the collection.
PostgreSQL accidentally update from Homebrew — OSX
By: Rahmat Ramadhan Irianto
Tags: OSX, Postgresql, Mac Os X, Django, Python

Error:

Django PostgreSQL Is the server running on host “localhost” (127.0.0.1) and accepting TCP/IP connections on port 5432?

After installing some tools from homebrew, I was just surprised that my PostgreSQL has been updated. And when I start the PostgreSQL and run python manage.py runserver it gives me output: django.db.utils.OperationalError: FATAL: role “databaseA” does not exist

I tried to make sure that the PostgreSQL has the previous data

$ /usr/local/Cellar/postgresql/13.1/bin/pg_ctl -D /usr/local/var/postgres start

and it gave me output: The data directory was initialized by PostgreSQL version 12, which is not compatible with this version 13.1. pg_ctl: could not start server

Solutions:

$ brew uninstall postgresql or brew uninstall — ignore-dependencies postgresql

$ brew install postgresql@12

if you face “LOG: could not bind IPv6 address “::1”: Address already in use” try to see

$ ps auxw | grep post

$ kill -9 <PID> Then Run

$ /usr/local/Cellar/postgresql@12/12.5/bin/pg_ctl -D /usr/local/var/postgres start

Hope this helps!
How to use multiple decorators with Class Based Views in Django.
By: Shedrack Godson
Tags: Python Programming, Django

How to use multiple decorators with Class Based Views in Django. Shedrack Godson ·Dec 12, 2020

Let’s get into the point

Since Django 1.9, according to the official doc, it is possible to apply decorator in the next way:

You can define your list of decorators

decorators = [decorator1, decorator2]

Then import method_decorator

from django.utils.decorators import method_decorator

Then in your class view

@method_decorator(decorators, name=’dispatch’) class Xyz(): here goes your logics….

Note: name=’dispatch’ must be the name of a method of the decorated class.

Thanks.
Django — Creating Your First Model
Tags: Computer Science, Python Programming, Coding, Django, Python

Let’s create your first model.

Ensure you have models imported from django.db Create a class with an appropriate name (i.e. Customer) Define each data point that you wish to include for each Customer. The field classification in our example is commonly used (characters) and requires you to define the maximum length. Save the file and make it a consistent habit to migrate the changes to the database via these 2 commands (in your command prompt):

1. python manage.py makemigrations * Important 2. python manage.py migrate * Important

Your models.py file should look similar to this:

from django.db import models ESSENTIAL IMPORT





class Customer(models.Model): MODEL NAME name = models.CharField(max_length=20) DATA FIELDS

email = models.CharField(max_length=20)

There are numerous field types to use in your models depending on the data you wish to collect. Commonly used field types are displayed below:

AutoField EmailField

BooleanField FloatField

CharField ImageField

DateTimeField IntegerField

DecimalField TextField

The changes have now been made to the database and you’re almost there. Next, open the settings.py file, import the model and then register it to the admin component of your website. You will now be able to view and make changes in your admin panel.

~ settings.py from django.contrib import admin

from .models import Customer



admin.site.register(Customer)

In regards to the admin panel it can also be helpful to return an __str__ function for each model. Each model item will then be labelled and more organised (particularly with larger data sets).

class Customer(models.Model): name = models.CharField(max_length=20)

email = models.CharField(max_length=20)

def __str__(self):

return self.name

After creating several entries each name will now clearly display in your admin page.

That’s it! Creating models is a core pillar of Django and can become much more advanced depending on the complexity of your database and how models relate to each other.

Further help can be found in the official documentation here.
any and all functions in python
By: Ali Soltani
Tags: Python Programming, Python, Django

In this tutorial, we will take a look at any and all functions in python and will give some examples.

any:

This function acts like or operator in python.

Examples for or operator:

(4==4) or (5==1)

> True (6==7) or (4==2)

> False (3==3) or (6==5) or (4==1)

> True (False or True or False)

> True (False or False or False)

> False (True or True or True)

> True

any takes an iterator as an argument and if one of the elements in iterator is true the result will be true.

Examples for any :

any([True, True, True])

> True any([False, True, False])

> True any([False, False, False])

> True any([True, False, True])

> True any([1==1, 3==1])

> True

If we pass an empty iterator to any, the result will be False.

any([])

> False

An example with a dictionary:

any({True: False, False: False})

> True

The result will be True, but why?

Because any looks at keys in the dictionary, not values.

all:

This function acts like and operator in python.

Examples for and operator:

(4==4) and (5==1)

> False (6==6) and (4==4)

> True (3==3) and (6==5) and (4==1)

> False (False and True and False)

> False (False and False and False)

> False (True and True and True)

> True

all takes an iterator as an argument and if all of the elements in iterator is true the result will be true.

Examples for all :

all([True, True, True])

> True all([False, True, False])

> False all([False, False, False])

> False all([True, False, True])

> False all([1==1, 3==1])

> False all([2==2, 3==3])

> True

If we pass an empty iterator to all, the result will be True.

all([])

> True

An example with a dictionary:

all({True: False, True: False})

> True

When we want to check many conditions, we can use any and all :

if condition1 or condition2 or condition3:

pass

Can be written like:

conditions = [condition1, condition2, condition3] if any(conditions):

pass if condition1 and condition2 and condition3:

pass

Can be written like:

conditions = [condition1, condition2, condition3] if all(conditions):

pass

See? now it’s more readable.
Worst Python Django Mistakes and How to Fix Them ?
Tags: Django

Worst Python Django Mistakes and How to Fix Them ?

Worst Python Django Mistakes and How to Fix Them ?

Django Developer Confuse in Between the STATIC_ROOT and STATICFILES_DIR :

Static files will not change as long as you are using the app. Such files include CSS, fonts, JavaScript, etc. Collect them in a public directory if you are using Django. Django uses the STATICFILES_FINDERS setting to search for all static files. You can write reusable applications and ship them in private static files. During production, you use a standalone server such as Nginx, which does not know anything about Django project applications. Django just gives the right static management command and copies every static file from various folders. The static data resources use the same logic with the Django development server. In your production environment, remember to run COLLECTSTATIC.

2. Integration Complex Techniques using the Simple Code :

If you integrate your new code with tools like JavaScript, you’ll be fixing your program for failure. it’s going to not run if you are doing not exercise caution in your integration. You will emerge as an honest developer if you specialise in improving yourself every day . Don’t consider the mistakes you made yesterday, just learn from them and advance . Test yourself by starting a project from scratch, and always confirm you carry it through to completion. If you’ve been a Django developer, you want to have made mistakes. Share them within the comment section below!

3. Django Developer Incorrect placement of resources and poor application of structure :

Every Django project has multiple applications. consistent with Django notation, a Python package which has applications containing files in current Django versions isn’t enough. Django applications have Python modules like management commands, static files, unit tests, database migrations, and Django specific modules (admin forms, URLs, template tags, views, etc.). Use simple logic to separate your monolith applications into reusable applications. Describe what your app does in simple sentences, like “allows users to check in and leave a comment.” Name the project folder, and store all dependencies in separate folders.

4 . Forget to put DEBUG = FALSE in the production sometimes :

Whenenver we are initializing the Django Project , Then we get some default files like settings.py . that is the only file where we can make or put verious connection values with other source so testing purpose on the local environmnet we put the Flag DEBUG= TRUE , because whenever make change to the settings.py with updates then it shows us the actually error if we miss some . So , while making the application being in the live environment we must have note to avoid the ethical hack on our website and avoid the exploitation of the urls of our project structure .