python -m venv virt: This command creates a new Python virtual environment named "virt" in the current directory.
virt/scripts/activate: This command activates the virtual environment, allowing you to use the Python and pip binaries from the virtual environment.
pip install django: This command installs the Django web framework in the current virtual environment.
django-admin startproject fossils: This command creates a new Django project named "fossils" in the current directory.
cd fossils: This command changes the current directory to the newly created "fossils" directory.
python manage.py migrate: This command applies any outstanding database migrations to the database.
python manage.py createsuperuser: This command creates a new superuser for the Django admin interface.
ni .gitignore: This command creates a new file named ".gitignore" in the current directory, which is used to specify files and directories that should be ignored by Git.
ni .env: This command creates a new file named ".env" in the current directory, which can be used to store environment variables.
python manage.py startapp app_fossils: This command creates a new Django app named "app_fossils" in the current directory.
pip install python-decouple: This command installs the python-decouple library, which can be used to store configuration settings in a separate file.
pip freeze > requirements.txt: This command saves a list of installed Python packages and their versions to a file named "requirements.txt".
python manage.py runserver: This command starts the Django development server, allowing you to view your web application in a web browser.
STEP 2: Update the .env file.
.env and SECRET_KEY
In a Django web application, the SECRET_KEY is a random string that is used to sign cookies, sessions, and other security-critical features of the application. It's essential that the SECRET_KEY remains secret, because if an attacker gets hold of it, they can use it to impersonate your users, bypass security features, and potentially take over your application.
Therefore, generating a strong and unique SECRET_KEY is important to keep your application secure. You should never hard-code your SECRET_KEY in your application code or version control system, as this makes it easier for an attacker to discover.
Instead, one best practice is to store the SECRET_KEY in an environment variable or a .env file, and then retrieve it in your Django settings file using a package like python-decouple. By using python-decouple, you can keep your secrets separate from your codebase and more secure, making it harder for an attacker to discover.
Navigate to https://djecrety.ir/, generate a new secret key and paste it inside the .env file:
SECRET_KEY = ‘_your_generated_key_here_’
STEP 3: Create folders in the root (fossils) directory.
Project folders
app_fossils\templates\app_fossils - This is where Django will look for HTML templates specific to the "app_fossils" app.
media - This folder is typically used to store user-uploaded files such as images or videos.
static - This folder is used to store static files such as CSS, JavaScript, or image files that are used throughout your project.
static\app_fossils\css, images, js - This folder is used to store static files such as CSS, JavaScript, or image files that are specific to the "app_fossils" app.
static\project - This folder is used to store static files that apply to the entire project and not just one individual app.
templates - This is where you can store HTML templates that are used across the entire project, such as the navbar or the base template. By having a separate folder for these templates, you can avoid duplicating code and make it easier to make changes across the entire project.
ALLOWED_HOSTS is a Django setting that defines a list of valid hostnames that can be used to access your website. When a request is received by the Django server, it checks the Host header of the request against the list of allowed hosts. If the Host header is not in the list, the request is rejected and a "Bad Request" (400) response is returned.
In development, it is common to add '127.0.0.1' and 'localhost' to ALLOWED_HOSTS. This is because you typically run the development server on your local machine, and these are the two most common ways to access the server locally. By adding these to the list of allowed hosts, you prevent Django from rejecting requests from your local machine.
In production, you should only include the hostnames that are actually allowed to access your server, such as the domain name of your website. If you add an incorrect hostname to the list of allowed hosts, an attacker could potentially spoof the Host header and gain access to your server.
To enhance the security of ALLOWED_HOSTS in production, you should also consider using HTTPS instead of HTTP. HTTPS encrypts the communication between the server and the client, making it much harder for an attacker to intercept or modify the Host header. Additionally, you can use a Content Security Policy (CSP) to further restrict the domains that are allowed to make requests to your server.
Add your app to the installed apps (the name will be the same as the class name found in apps.py):
In Django's settings.py file, the 'DIRS' option is used to specify a list of directories where Django should look for template files. os.path.join(BASE_DIR, 'templates') adds a directory called 'templates' that is located in the base directory of the project (BASE_DIR) to the list of directories to search for templates.
This 'templates' directory in the project's root folder is typically used to store template files that are shared across the entire project, such as base.html and navbar.html. These files provide a consistent look and feel across all pages of the website. Unlike the 'templates' directory located within individual apps, which is used to store templates specific to that app, the root 'templates' directory is not associated with any specific app and is used for templates that apply to the entire project.
os.path.join() is a Python method that is used to join two or more paths together. In this case, it is used to join the base directory (BASE_DIR) and the 'templates' directory together, creating a complete path to the templates directory.
In Django, STATICFILES_DIRS is a setting that specifies additional directories where Django should look for static files (CSS, JavaScript, images, etc.). By default, Django looks for static files in each app's 'static' directory.
os.path.join(BASE_DIR, 'static') adds a directory called 'static' that is located in the base directory of the project (BASE_DIR) to the list of directories to search for static files.
So, this command tells Django to look for static files in the 'static' directory located in the project's base directory in addition to the 'static' directories located within each app. This is useful for static files that are shared across multiple apps.
You should define MEDIA_ROOT in your Django settings file if your project needs to handle file uploads or serve media files. In development, you may choose to store media files locally using MEDIA_ROOT. However, in a live production environment, you may need to configure MEDIA_ROOT to point to a cloud storage provider like Amazon S3. It's important to keep in mind that the specific configuration of MEDIA_ROOT may vary depending on your production environment and your preferred way of storing and serving media files.
By default, Django automatically handles user authentication and redirects users to specific pages after login or logout.
This behavior is controlled by two settings in your Django settings file: LOGIN_REDIRECT_URL and LOGOUT_REDIRECT_URL.
You can customize these settings to achieve different behavior. For example, you could redirect users to a specific page after login, such as a dashboard or profile page. Similarly, you could redirect users to a custom logout page that displays a confirmation message or performs additional actions.
STEP 5: urls.py - main project level: include
& admin
To serve media files in development mode, you need to set two variables in your settings.py file: MEDIA_URL and MEDIA_ROOT. MEDIA_URL is the base URL for your media files, such as /media/. MEDIA_ROOT is the absolute path of the directory where you store your media files, such as /home/user/project/media/.
You also need to add a URL pattern to your urls.py file that maps your MEDIA_URL to your MEDIA_ROOT. You can do this by using a helper function called static() from django.conf.urls.static module. This function takes two arguments: settings.MEDIA_URL and document_root=settings.MEDIA_ROOT. It returns a list of URL patterns that match your media files with their locations on disk.
You can append this list of URL patterns to your existing urlpatterns list by using + operator. This way, you don’t have to write each URL pattern manually for each media file.
However, this method only works in development mode when debug=True. In production mode, Django does not serve media files by itself. You need to configure your web server (such as Apache or Nginx) to serve them directly.
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include
from django.http import HttpResponse
def restricted(request):
return HttpResponse("Access to the admin area is restricted.")
urlpatterns = [
path('admin/', restricted),
path('secret_admin/', admin.site.urls),
path("", include("app_fossils.urls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Include
In a Django project, each app can have its own URLs that define the endpoints and views for that app. However, to make these URLs accessible to the project as a whole, they need to be included in the main project's URLs.
This is done using the include() function in the main urls.py file. The include() function takes as its argument the path to the app's urls.py file. For example, path("", include("app_fossils.urls")) would include the URLs defined in the urls.py file of the app_fossils app.
By including an app's URLs in the main project's URLs, requests to those endpoints can be properly routed to the appropriate view functions. This allows for greater organization and modularity within a Django project, as each app can define its own URLs and views without interfering with the rest of the project.
Additionally, including app URLs in the main project URLs allows for easier maintenance and scalability of the project, as new apps can be added without affecting the existing codebase.
Admin
The /admin URL is the default URL used by Django's built-in administration interface, which provides a way for administrators to manage the data and functionality of the web application. However, because the /admin URL is well-known and easy to guess, it is a common target for attackers who are looking to gain unauthorized access to the administration interface.
By changing the default /admin URL to something else, you can make it more difficult for attackers to find the URL and attempt to access the administration interface. This can help to improve the security of your web application and protect sensitive data and functionality from unauthorized access.
STEP 6: urls.py - app level (create the file first)
from django.urls import path
from django.http import HttpResponse
def urls_test(request):
return HttpResponse("Urls set up correctly")
urlpatterns = [
path('', urls_test),
]
STEP 7: Run project
After completing the setup process, you can now run the server by executing the command 'python manage.py runserver'. Once the server is running, you can access the web application by navigating to the following URLs in your web browser:
Navigate to the "templates" folder located directly in the root directory of your project and reate two new files: "base.html" and "navbar.html".
navbar.html
Go to the Bootstrap website https://getbootstrap.com/, navigate to the "docs" section and locate the "navbar" component. Copy the provided HTML code and paste it into the "navbar.html" file.
base.html
Favicon: Obtain a favicon and save it in the "static\project" folder under your project's root directory. You can use websites such as https://icon-icons.com/ to obtain a favicon or convert a .jpg image to an .ico file using https://icon-icons.com/.
If you include a tag referencing a favicon, but the corresponding favicon image file is not present in the static files, you may encounter an unexpected issue preventing you from disabling Django's debug mode when deploying your project to a live environment.
Bootstrap: Navigate to the Bootstrap website and obtain the current CSS and JS links.
At this point we can delete the urls_test function and and the corresponding path.
Next we have to import views: from . import views and create a new URL pattern:
from django.urls import path
from app_fossils.views import *
urlpatterns = [
path('', home, name='homepage'),
]
Step 9.4: Use the new url: open navbar.html and add the new ‘homepage’ url
STEP 10: GitHub
GitHub
GitHub is a web-based platform for version control and collaboration that provides a way for developers to manage and share their code. It is commonly used to host open source projects, as well as private repositories for individuals and teams.
Setting up a GitHub repository early in the process of creating a new Django project can have several benefits:
Version control: GitHub provides a robust version control system that allows developers to keep track of changes to their code over time. This can help you keep track of changes to your project and easily roll back to a previous version if needed.
Collaboration: GitHub makes it easy for multiple developers to work on the same project simultaneously. With GitHub, you can create branches for new features or bug fixes, and then merge those changes back into the main codebase when they're ready.
Backup and recovery: By hosting your code on GitHub, you automatically get a backup of your code in the cloud. This means that even if something happens to your local computer, your code is safe and can be recovered easily.
Community engagement: Hosting your code on GitHub can help you connect with other developers who are interested in your project. This can lead to contributions, bug reports, and other forms of engagement that can help improve your project over time.
# Ignore database files
*.db
*.sqlite3
# Ignore media files
/media/
# Ignore compiled Python files
*.pyc
__pycache__/
# Ignore environment variables file
.env
# Ignore local settings file
local_settings.py
# Ignore IDE configuration files
.idea/
.vscode/
# Ignore migration files
*/migrations/*.py
*/migrations/*.bak
*/migrations/*.swp
*/migrations/*.pyc
*/migrations/__pycache__/
# Ignore log files
*.log
# Ignore message files created by Django's internationalization framework
*.pot
# Ignore SQLite database files
db.sqlite3
# Ignore media files that are uploaded to the server
media
# Ignore virtual environment directories
.venv/
env/
venv/
ENV/
virt/
virtual/
env.bak/
venv.bak/
# Ignore secret key file
secret_key.txt
# Ignore system files
.DS_Store
Thumbs.db
.gitignore
.gitignore file is used to specify files or directories that should be ignored by Git when tracking changes to a project. This is useful when working on a project that has files or directories that should not be committed to the repository, such as temporary files, log files, or sensitive information like passwords or API keys. The .gitignore file specifies which files or directories to ignore by using patterns or wildcard characters. When Git encounters a file or directory that matches a pattern in the .gitignore file, it will ignore it and not include it in the project's commit history.
Step 10.2: Create a new repository
Go to https://github.com/ and either log in or register for an account.
Once you're logged in, navigate to https://github.com/new to create a new repository.
Add a name for your repository (e.g. "fossils") and click on the "Create repository" button.
Copy the Git address for your new repository. It should be in the format: https://github.com/your_username/fossils.git.
Open Visual Studio Code and go to "File" -> "Open Folder".
Navigate to the main folder for your Django project (e.g. "fossils_project") and select the "fossils" subfolder, then click "Select Folder".
In Visual Studio Code, open a new terminal by clicking on "Terminal" -> "New Terminal".
In the terminal, run the following commands one by one
cd..
virt/scripts/activate
cd fossils
git init
git add .
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/_replace_with_your_username_/fossils.git
git push -u origin main
Commands
cd..: Move up one directory level to your project root.
virt/scripts/activate: Activate the virtual environment.
cd fossils: Move into the "fossils" subdirectory.
git init: Initialize a new Git repository in this directory.
git add .: Add all files in the current directory to the Git repository.
git commit -m "first commit": Create a new commit with the message "first commit".
git branch -M main: Rename the default branch to "main".
git remote add origin https://github.com/your_username/fossils.git: Add the remote repository on GitHub as "origin".
git push -u origin main: Push the local "main" branch to the "origin" remote repository on GitHub.
Going forward, whenever you make changes to your code, you can use the following commands to push the updates to your main branch on GitHub:
User authentication is a crucial feature for any web application that involves user data and interactions. It allows users to register, log in, and access their own data securely and conveniently.
Setting up user authentication early in the development process is important for several reasons:
It helps you design your app with user data and permissions in mind.
It saves you time and effort later on. You don't have to refactor your code or migrate your database to add user authentication features after you have already built other parts of your app.
It prevents security risks and errors. You can avoid exposing sensitive data or allowing unauthorized actions by implementing user authentication from the start.
One way to simplify the process of setting up user authentication in Django is to use a third-party package such as django-allauth. django-allauth is a comprehensive solution that offers:
User registration with email confirmation and password reset
Social account integration with various providers such as Google, Facebook, Twitter, etc.
Customizable templates and forms for login, signup, profile, etc.
Extensible functionality with signals and adapters