{"id":21908965,"url":"https://github.com/jayhawk24/webdev_notes","last_synced_at":"2026-04-24T11:32:08.556Z","repository":{"id":130218967,"uuid":"304608658","full_name":"jayhawk24/WebDev_Notes","owner":"jayhawk24","description":null,"archived":false,"fork":false,"pushed_at":"2020-10-31T10:04:25.000Z","size":181,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-22T07:48:20.762Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jayhawk24.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-10-16T11:35:18.000Z","updated_at":"2020-10-31T10:04:28.000Z","dependencies_parsed_at":null,"dependency_job_id":"ffd0cdae-0d53-455a-b173-26ab14099a27","html_url":"https://github.com/jayhawk24/WebDev_Notes","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/jayhawk24/WebDev_Notes","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jayhawk24%2FWebDev_Notes","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jayhawk24%2FWebDev_Notes/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jayhawk24%2FWebDev_Notes/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jayhawk24%2FWebDev_Notes/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jayhawk24","download_url":"https://codeload.github.com/jayhawk24/WebDev_Notes/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jayhawk24%2FWebDev_Notes/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":263290788,"owners_count":23443657,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-28T17:14:30.964Z","updated_at":"2026-04-24T11:32:08.523Z","avatar_url":"https://github.com/jayhawk24.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Mordern Web Technologies Courses Notes\n\n## Django\n- Django Project is a collection if application and configurations that when combined together will make up the full web application.\n- A django application is created to perform a particular functionality for our entire web application. like polling app, comments app. etc..\n- They are reusable or plugable django apps.\n\n\n### Init Commands\n```\n    python3 -m venv proj-name\n    source bin/activate\n    pip3 install django\n    django-admin startproject name\n```\n\n#### Config files\n\n- __init__.py\n  - Blank python script that due to its special name let's python know that his directory can be treated as a package.\n- settings.py\n    - this is where we store project settings.\n- urls.py\n    - stores all the URL patterns for your project . Basically the different pages of your web application.\n- wsgi.py\n  - This script acts as the web server gateway interface. it wil later on help us deploy our web app to production.\n- manage.py\n  - most used\n  - It will be associated with many commands .\n\n\n#### Migration\n- migration allows us to move databases from one design to another, this is also reversible.\n- So we can migrate our database\n\n### App starting commands\n```\n  python manage.py startapp first_app\n\n```\n#### App files\n- apps.py\n  - here we place application specific configurations.\n- models.py\n  - here we store applications data model.\n- tests.py\n  - here we can store test functions to test our code.\n- views.py\n  - this is where we have functions that handle requests and return responses\n- Migrations folder\n  - stores database specific information as it relates to the models\n\n#### Steps To Add an App\n- First start an app.\n- add app name under settings.py file.\n- in views.py file import HttpResponse from django.http.\n- create a function in views.py called index.\n- add URL in url pattern .\n  \n### URL Mapping\n- create a urls.py file inside app directory which is same as urls.py file in project directory\n- include app.urls.py file in project.urls.py file\n  ```\n  from django.conf.urls import \n  urlpatterns = [\n    path('yourpath/',include('app.urls')),\n  ]\n  ```\n- include views in app.urls.py file\n### Add Template\n- add template directory in settings.py after creating a template directory\n  \n  ```\n  import os\n  TEMPLATE_DIR = os.path.join(BASE_DIR,\"template's_foldername\")\n  ```\n\n- Then create index.html in template folder use {{ insert_me }} to inject dictionary variables.\n- go to views.py in first_app and use this function\n  ```\n  def index(request):\n    myDict = {\"insert_me\":\"This is injected to index.html\"}\n    return render(request,'first_app/index.html',context=myDict)\n  ```\n\n### Add Static files\n- Add STATIC_DIR variable in project.settings.py as the path for static directory.\n- At the bottom add STATICFILES_DIRS = [STATIC_DIR,] \n- In index.html below doctype html add template tag as below\n  ```\n  {% load static %}\n  \u003clink rel=\"stylesheet\" href=\"{% static 'css/style.css'%}\"\u003e\n  ```\n\n### Add Models\n- to add models we first define classes in models.py file in first_app directory as table names and inside variables as columns like\n  ```\n\n  class Webpage(models.Model):\n      topic = models.ForeignKey(Topic, on_delete=models.CASCADE,)\n      name = models.CharField(max_length=256, unique=True)\n      url = models.URLField(unique=True)\n\n      def __str__(self) -\u003e str:\n          return self.name\n  ```\n- Then run command\n  ```\n  python3 manage.py migrate\n\n  python manage.py makemigrations first_app\n  python manage.py migrate\n  ```\n\n### Add Admin Page\n- import all models from models.py\n- use this command to register\n  ```\n  from first_app.models import *\n\n  admin.site.register(modelname)\n  ```\n- create a super user\n- python3 manage.py createsuperuser\n\n### Connecting Models, Templates, Views\n- In views.py file we import any models that we will need to use.\n- Use the view to query the model for data that we will need\n- pass results from the model to the template.\n- Edit template so that it is ready to accept and display the data from the model.\n- Map a url to the view.\n\n### Script to populate models\n```\nfrom faker import Faker\nimport os\nimport django\n\ndjango.setup()\n\n\nfrom apptwo.models import *\n\nfakegen = Faker()\n\n\ndef populate(N=10):\n    for entry in range(N):\n        print(5)\n        fname = fakegen.name().split()[0]\n        lname = fakegen.name().split()[0]\n        email = fakegen.email()\n\n        us = User.objects.get_or_create(\n            firstName=fname,\n            lastName=lname,\n            email=email\n        )[0]\n\nif __name__ == \"__main__\":\n    print(\"Running scripts\")\n    populate(int(input(\"Number of data to be added.\")))\n```\n\n### Adding forms\n- Add form view function in views.py file\n  \n```\n  def formview(request):\n    form = forms.formName()\n\n    if request.method == 'POST':\n        form = forms.formName(request.POST)\n\n        if form.is_valid():\n            print(\"Validation success\")\n            print(\"Name : \"+form.cleaned_data[\"name\"])\n            print(\"Email : \"+form.cleaned_data[\"email\"])\n            print(\"Text : \"+form.cleaned_data[\"text\"])\n\n    return render(request,'forms.html',{'form':form})\n```\n- add this view to urls.py file\n- In forms.html file create a form using\n```\n{{form.as_p}}\n{% csrf_token %}\n```\n### Saving Data from forms\n- create a forms.py file inside app. import models\n```\n  from django import forms\n  from apptwo.models import User\n\n\n  class NewUserForm(forms.ModelForm):\n    class Meta:\n        model = User\n        fields = '__all__'\n```\n- Now inside views.py file import Newuserform class created in forms.py file\n\n```\n\ndef signup(request):\n\n    form = NewUserForm()\n\n    if request.method == \"POST\":\n        form = NewUserForm(request.POST)\n\n        if form.is_valid():\n            form.save(commit=True)\n            return index(request)\n        else:\n            print(\"Invalid Form\")\n    \n    return render(request,'signup.html',context={'form':form})\n  \n```\n\n### Templating Urls\n- {% url 'basic_app:other' %} in html page\n- where basic_app is a variable assigned as app_name inside urls.py file in app folder\n- and other is the name of the page to be directed to it.\n- this name should be defined in urls.py file\n- path('other', views.other, name=\"other\"),\n  \n### Template Inheritance\n- in your base.html file put up all the stuff you would like to inherit and at bottom inside a div container add a template tag\n```\n        {% block body_block %}\n\n        {% endblock %}\n```\n- now in your rest of HTML file all you need to to is after declaring doctype give this\n```\n    {% extends \"basic_app/base.html\" %}\n    \n    {% block body_block %}\n\n    \u003ch2\u003eWelcome to other\u003c/h2\u003e\n    \n    \u003ch3\u003eInherited \u003c/h3\u003e\n    {% endblock %}\n```\n### Saving Username and passwords\n- Create a model which will inherit default User model which contains username and password fields.\n  ```\n  from django.db import models\n  from django.contrib.auth.models import User\n\n  class UserProfileInfo(models.Model):\n\n    user = models.OneToOneField(User, on_delete=models.DO_NOTHING)\n    \n    portfolioSite = models.URLField(blank=True)\n\n    profilePic = models.ImageField(upload_to='profilePics', blank=True)\n\n    def __str__(self) -\u003e str:\n        return self.user.username\n  ```\n- Add Password hashers in settings.py \n```\nPASSWORD_HASHERS = [\n    'django.contrib.auth.hashers.Argon2PasswordHasher',\n    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',\n    'django.contrib.auth.hashers.BCryptPasswordHasher',\n    'django.contrib.auth.hashers.PBKDF2PasswordHasher',\n    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',\n]\n```\n- In forms.py file \n```\nfrom django import forms\nfrom django.contrib.auth.models import User\nfrom django.forms import fields\nfrom basic_app.models import UserProfileInfo\n\n\nclass UserForm(forms.ModelForm):\n    password = forms.CharField(widget=forms.PasswordInput())\n\n    class Meta():\n        model = User\n        fields = (\"username\",\"email\",\"password\")\n\n\nclass UserProfileInfoForm(forms.ModelForm):\n    class Meta():\n        model = UserProfileInfo\n        fields = ('portfolioSite','profilePic')\n```\n- In views.py file create a function to save data \n```\nfrom django.http import request\nfrom basic_app.forms import UserForm,UserProfileInfoForm\nfrom django.shortcuts import render\n\n# Create your views here.\n\ndef index(request):\n    return render(request,\"index.html\")\n\ndef register(request):\n    \n    registered = False\n\n    if request.method == 'POST':\n        user_form = UserForm(data=request.POST)\n        profile_form = UserProfileInfoForm(data=request.POST)\n\n        if user_form.is_valid() and profile_form.is_valid():\n\n            user = user_form.save()\n            user.set_password(user.password)\n            user.save()\n\n            profile = profile_form.save(commit=False)\n            profile.user = user\n\n            if 'profile_pic' in request.FILES:\n                profile.profile_pic = request.FILES['profile_pic']\n            \n            registered = True\n    \n        else:\n            print(user_form.errors, profile_form.errors)\n    else:\n        user_form = UserForm()\n        profile_form = UserProfileInfoForm()\n\n    return render(request, 'registration.html',\n                {'user_form':user_form,\n                'profile_form':profile_form,\n                'registered':registered}\n    )\n```\n- In registration.html file\n```\n\u003c!DOCTYPE html\u003e\n{% extends 'base.html' %}\n\n{% load static %}\n\n{% block body_block %}\n\n    \u003cdiv class=\"jumbotron\"\u003e\n        {% if registered %}\n        \u003ch1\u003e Thank you for registering!\u003c/h1\u003e\n        {% else %}\n        \u003ch3\u003e Fill out the form : \u003c/h3\u003e\n\n        \u003cform method=\"POST\" enctype=\"multipart/form-data\"\u003e\n            {% csrf_token %}\n            {{ user_form.as_p}}\n\n            {{ profile_form.as_p }}\n            \u003cinput type=\"submit\" name=\"\" value=\"Register\"\u003e\n\n\n        \u003c/form\u003e     \n        {% endif %}\n\n    \u003c/div\u003e\n{% endblock  %}\n```\n### Including User Login\n- imports and functions in views.py\n```\n\nfrom django.contrib.auth import authenticate,login,logout\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required\n\n\ndef user_login (request):\n\n    if request.method == \"POST\":\n        username = request.POST.get('username')\n        password = request.POST.get('password')\n        user = authenticate(username=username, password=password)\n\n        if user:\n            if user.is_active:\n                login(request, user)\n                return HttpResponseRedirect(reverse('index'))\n\n            else:\n                return HttpResponse(\"Account not active\")\n\n        else:\n            print(\"Someone tried to login and failed!\")\n            print(\"username: {} and password {}\".format(username,password))\n            return HttpResponse(\"Invalid Login details supplied!\")\n    \n    else:\n        return render(request,'login.html',{})\n\n```\n- In login.html\n```\n{% extends 'base.html' %}\n\n{% block body_block %}\n\n\u003cdiv class=\"jumbotron\"\u003e\n    \u003ch1\u003ePlease Login\n    \u003c/h1\u003e\n    \u003cform action=\"{% url 'user_login' %}\" method=\"POST\"\u003e\n        {% csrf_token %}\n\n        \u003clabel for=\"username\"\u003eUsername:\u003c/label\u003e\n        \u003cinput type=\"text\" name=\"username\" placeholder=\"Enter Username\"\u003e\n\n        \u003clabel for=\"password\"\u003ePassword:\u003c/label\u003e\n        \u003cinput type=\"password\" name=\"password\"\u003e\n\n        \u003cinput type=\"submit\" name=\"\" value=\"Login\"\u003e\n        \n    \u003c/form\u003e\n\u003c/div\u003e\n\n{% endblock  %}\n```\n\n### Class Based Views\n- We have to first import from jango.views.generic View and TemplateView and then create a class.\n- ```\n  from django.views.generic import View,TemplateView\n\n  class IndexView(TemplateView):\n    template_name = 'index.html'\n\n    def get_context_data(self,**kwargs):\n      context = super().get_context_data(**kwargs)\n      context['tobeinjected'] = \"basic injection\"\n      return context\n\n  ```\n- Then in urls.py file we declare it as...\n- ```path(\"\", views.IndexView.as_view())```\n\n#### List view and detail view\n- Say we have 2 models namely school and students.\n- we can list the views as...\n```\nfrom django.views.generic import View,TemplateView,ListView,DetailView\n\nclass schoolListView(ListView):\n  model = models.School\n\n  # this returns context dictionary as school_list by default\n  # to change name we can do \n  context_object_name = \"schools\"\n\n\nclass schoolDetailView(DetailView):\n  model = models.School\n  template_name = 'school.html'\n\n\n```\n\n### To link every list view with its details check out advcbv CRUD operations with CBVs \n- check out advcbv project\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjayhawk24%2Fwebdev_notes","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjayhawk24%2Fwebdev_notes","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjayhawk24%2Fwebdev_notes/lists"}