{"id":20067959,"url":"https://github.com/makiato1999/backend-django-notes","last_synced_at":"2025-07-03T15:37:50.665Z","repository":{"id":43076633,"uuid":"511038003","full_name":"Makiato1999/Backend-Django-Notes","owner":"Makiato1999","description":"Notes about Coursera course Django for Everybody Specialization by Xiaoran Xie","archived":false,"fork":false,"pushed_at":"2022-11-12T09:01:47.000Z","size":1741,"stargazers_count":0,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-02T11:18:57.600Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","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/Makiato1999.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}},"created_at":"2022-07-06T07:40:58.000Z","updated_at":"2023-03-22T06:59:03.000Z","dependencies_parsed_at":"2022-07-18T10:39:33.690Z","dependency_job_id":null,"html_url":"https://github.com/Makiato1999/Backend-Django-Notes","commit_stats":null,"previous_names":["makiato1999/backend-django-notes"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Makiato1999/Backend-Django-Notes","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Makiato1999%2FBackend-Django-Notes","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Makiato1999%2FBackend-Django-Notes/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Makiato1999%2FBackend-Django-Notes/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Makiato1999%2FBackend-Django-Notes/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Makiato1999","download_url":"https://codeload.github.com/Makiato1999/Backend-Django-Notes/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Makiato1999%2FBackend-Django-Notes/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":263351268,"owners_count":23453441,"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-13T14:04:39.886Z","updated_at":"2025-07-03T15:37:50.636Z","avatar_url":"https://github.com/Makiato1999.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Django for Everybody Specialization\n_provided by University of Michigen \u0026 Coursera_\n#### Table of Contents\n1. [Web Application Technologies and Django](#anchor_4)\n   - [If db gets messed up](#anchor_41)\n   - [django document 01(intro), 02(model, migration)](#anchor_42)\n2. [Building Web Applications in Django](#anchor_5)\n   - [django document 03(url.py, views.py, templete(html))](#anchor_51)\n   - [django document 04(forms, GET, POST, generic views)](#anchor_52)\n3. [Django Features and Libraries](#anchor_6)\n   - [Building a Main Page](#anchor_61)\n   - [CRUD](#anchor_62)\n   - [one-to-many](#anchor_63)\n   - [many-to-many](#anchor_64)\n4. [Using JavaScript, JQuery, and JSON in Django](#anchor_7)\n   - [first class function](#anchor_71)\n## Web Application Technologies and Django\u003ca name=\"anchor_4\"\u003e\u003c/a\u003e\n1. Model-View-Controller\n   - Model: The persistent data that we keep in the data store\n   - View: Html, Css, etc. which makes up the look and feel of the application\n   - Controller: The code that does the thinking and decision making\n   - Which of the following files does Django consult first when it receives an incoming HTTP Request?\n      - urls.py\n2. SQL summary\n   - ```INSERT INTO Users (name, email) VALUES ('Kristina', 'kf@uofm.ca')```\n   - ```DELETE FROM Users WHERE email='ted@uofm.ca'```\n   - ```UPDATE Users SET name=\"Shawn\" WHERE email='csev@uofm.ca'```\n   - ```SELECT * FROM Users```\n   - ```SELECT * FROM Users WHERE email='csev@uofm.ca'```\n   - ```SELECT * FROM Users ORDER BY email'```\n3. Object Relational Mapping\n4. CRUD in the ORM\n   - ```INSERT INTO Users (name, email) VALUES ('Kristina', 'kf@uofm.ca')```\n     \u003cbr\u003eis same as:\n     ```\n     u = User(name='Kristina', email='kf@uofm.ca')\n     u.save()\n     ```\n   - ```SELECT * FROM Users```\n     \u003cbr\u003eis same as:\n     ```\n     User.objects.values()\n     ```\n   - ```SELECT * FROM Users WHERE email='csev@uofm.ca'```\n     \u003cbr\u003eis same as:\n     ```\n     User.objects.filter(email='csev@uofm.ca').values\n     ```\n   - ```UPDATE Users SET name=\"Shawn\" WHERE email='csev@uofm.ca'```\n     \u003cbr\u003eis same as:\n     ```\n     User.objects.filter(email='csev@uofm.ca').update(name='Shawn')\n     ```\n   - ```SELECT * FROM Users ORDER BY email'```\n     \u003cbr\u003eis same as:\n     ```\n     User.objects.values().order_by('email')\n     ```\n5. If db gets messed up (if you screw up)\u003ca name=\"anchor_41\"\u003e\u003c/a\u003e\n   - ```cd ~/django_projects/mysite/polls/```\n   - ```rm *migrations/00*```\n   - ```rm db.sqlite3```\n   - ```workon django3                  # as needed```\n   - ```python manage.py check```\n   - ```python manage.py makemigrations```\n   - ```python manage.py migrate```\n   - ```python manage.py check```\n   - ```python manage.py createsuperuser```\n7. What does the \"python manage.py migrate\" command do?\n   - Builds/updates the database structure for the project\n8. What is the purpose of the models.py file?\n   - To define the shape of the data objects to be stored in a database\n9. three-step guide to making model changes:\n   - Change your models (in models.py).\n   - Run ```python manage.py makemigrations``` to create migrations for those changes\n   - Run ```python manage.py migrate``` to apply those changes to the database.\n1. there are too many contents, read django document is a better way to study it\u003ca name=\"anchor_42\"\u003e\u003c/a\u003e\n   - [django tutorial01](https://docs.djangoproject.com/en/3.2/intro/tutorial01/)\n   - models and mogration [django tutorial02](https://docs.djangoproject.com/en/3.2/intro/tutorial02/)\n## Building Web Applications in Django\u003ca name=\"anchor_5\"\u003e\u003c/a\u003e\n1. views\n   - function based views\n      ```\n      # url:\n      # http://samples.dj4e.com/views/rest/41\n      \n      # url.py:\n      urlpatterns = [\n         path('rest/\u003cint:guess\u003e', view.rest),\n      ]\n      \n      # response:\n      from django.http import HttpResponse\n      from django.utils.html import escape\n      \n      def rest(request, guess):\n         response = \"\"\"\u003chtml\u003e\u003cbody\u003e\u003cp\u003e\"\"\"+escape(guess)+\"\"\"\u003c/p\u003e\u003c/body\u003e\u003c/html\u003e\"\"\"\n         return HttpResponse(response)\n      ```\n   - class based views\n      ```\n      # url:\n      # http://samples.dj4e.com/views/remain/xxr123-33-nbnb\n      \n      # url.py:\n      urlpatterns = [\n         path('remain/\u003cslug:guess\u003e', views.RestMainView.as_view()),\n      ]\n      \n      # response:\n      from django.http import HttpResponse\n      from django.utils.html import escape\n      from django.views import View\n      \n      Class RestMainView(View):\n         def get(self, request, guess):\n            response = \"\"\"\u003chtml\u003e\u003cbody\u003e\u003cp\u003e\"\"\"+escape(guess)+\"\"\"\u003c/p\u003e\u003c/body\u003e\u003c/html\u003e\"\"\"\n            return HttpResponse(response)\n      ```\n2. there are too many contents, read django document is a better way to study it\u003ca name=\"anchor_51\"\u003e\u003c/a\u003e\n   - url.py, views.py, templete(html) [django tutorial03](https://docs.djangoproject.com/en/3.2/intro/tutorial03/)\n3. render\n   ```\n   from django.shortcuts import render\n   from .models import Question\n   \n   def index(request):\n      latest_question_list = Question.objects.order_by('-pub_date')[:5]\n      context = {'latest_question_list': latest_question_list}\n      return render(request, 'polls/index.html', context)\n   ```\n4. Templates, most of them are HTML\n   - Django template language\n      - Removing hardcoded URLs in templates, this is the example:\n        - ```\u003cli\u003e\u003ca href=\"{% url 'polls:detail' question.id %}\"\u003e{{ question.question_text }}\u003c/a\u003e\u003c/li\u003e```\n      - other using ways, such as normal statement in python\n        - ```\n          {% if latest_question_list %}\n          \u003cul\u003e\n               {% for question in latest_question_list %}\n                  \u003cli\u003e\u003ca href=\"{% url 'polls:detail' question.id %}\"\u003e{{ question.question_text }}\u003c/a\u003e\u003c/li\u003e\n               {% endfor %}\n          \u003c/ul\u003e\n          {% else %}\n               \u003cp\u003eNo polls are available.\u003c/p\u003e\n          {% endif %}\n          ```\n       - in the form and using POST, we should take care about {% csrf_token %} \n         - ```\n           \u003cform action=\"{% url 'polls:vote' question.id %}\" method=\"post\"\u003e\n           {% csrf_token %}\n               \u003cfieldset\u003e\n                  \u003clegend\u003e\u003ch1\u003e{{ question.question_text }}\u003c/h1\u003e\u003c/legend\u003e\n                  {% if error_message %}\n                   \u003cp\u003e\u003cstrong\u003e{{ error_message }}\u003c/strong\u003e\u003c/p\u003e\n                  {% endif %}\n                  {% for choice in question.choice_set.all %}\n                     \u003cinput type=\"radio\" name=\"choice\" id=\"choice{{ forloop.counter }}\" value=\"{{ choice.id }}\"\u003e\n                     \u003clabel for=\"choice{{ forloop.counter }}\"\u003e{{ choice.choice_text }}\u003c/label\u003e\n                     \u003cbr\u003e\n                  {% endfor %}\n               \u003c/fieldset\u003e\n                     \u003cinput type=\"submit\" value=\"Vote\"\u003e\n           \u003c/form\u003e\n           ```\n6. there are too many contents, read django document is a better way to study it\u003ca name=\"anchor_52\"\u003e\u003c/a\u003e\n   - forms, GET, POST, generic views [django tutorial04](https://docs.djangoproject.com/en/3.2/intro/tutorial04/)\n7. a sqlite3 db has existed in https://makiato1999.pythonanywhere.com/polls, if you want to use admin, you should use \n   - Account: dj4e, Password: bc53a9938\n## Django Features and Libraries\u003ca name=\"anchor_6\"\u003e\u003c/a\u003e\n1. Building a Main Page/ add a new application\u003ca name=\"anchor_61\"\u003e\u003c/a\u003e\n   ```\n   workon django3                  # as needed\n   cd ~/django_projects/mysite\n   python3 manage.py startapp home\n   ```\n   Create an HTML file in ~/django_projects/mysite/home/templates/home/main.html\n   \u003cbr\u003e\n   dont forgot to update ~/django_projects/mysite/mysite/urls.py\n   ```\n   path('', TemplateView.as_view(template_name='home/main.html')),\n   ```\n   Then edit the file ~/django_projects/mysite/mysite/settings.py and add a line to load the home application.\n   ```\n   python3 manage.py check\n   ```\n2. cookies and session\n   - google to view difference \n   - how to create session and cookie in django, in views.py\n     ```\n     from django.http import HttpResponse\n\n     def myview(request):\n         num_visits = request.session.get('num_visits', 0) + 1\n         request.session['num_visits'] = num_visits\n         resp = HttpResponse('view count='+str(num_visits))\n         resp.set_cookie('dj4e_cookie', '37e3398f', max_age=1000)\n         return resp\n     ```\n3. login and logout\n   - form\n      - form/forms.py\n      ```\n      from django import forms\n      from django.core.exceptions import ValidationError\n      from django.core import validators\n   \n      class BasicForm(forms.Form):\n         title = forms.CharField(validators=[validators.MinLengthValidator(2, \"...\")])\n         mileage = forms.IntegerField()\n         purchase_date = forms.DataField()\n   \n      ``` \n      - form/views.py\n      ```\n      from form.forms import BasicForm\n      \n      def example(request):\n         form = BasicForm()\n         return HttpResponse(form.as_table)\n      ```\n      form.as_table() will create form html, so there is another way to write, we can put it in templete\n      - form/templete/form/form.html\n      ```\n      \u003cp\u003e\n         \u003cform action=\"\" method=\"post\"\u003e\n            {% csrf_token %}\n            \u003ctable\u003e\n               {{form.as_table}}\n            \u003c/table\u003e\n            \u003cinput type=\"submit\" value=\"Submit\"\u003e\n            \u003cinput type=\"submit\" onclick=\"window.location='{% url 'form:main'%}'; return false;\" value=\"Cancel\"\u003e\n         \u003c/form\u003e\n      \u003c/p\u003e\n      ```\n4. login and CRUD(create, read, update, delete)\u003ca name=\"anchor_62\"\u003e\u003c/a\u003e\n   - this assignment is hard -\u003e [week3 assignment](https://www.dj4e.com/assn/dj4e_autos.md?PHPSESSID=15b0d8e4bd0299496cc47e7134333eff)\n5. model and database, one-to-many\u003ca name=\"anchor_63\"\u003e\u003c/a\u003e\n   - keep the row but set foreign key to null\n   ```\n   lan = models.ForeignKey('Language', on_delete = models.SET_NULL, null = True)\n   ```\n   - delete the row\n   ```\n   lan = models.ForeignKey('Book', on_delete = models.CASCADE)\n   ```\n6. Cats CRUD assignment is almost same as autos CRUD\n   - assignment [week4 assignment document](https://www.dj4e.com/tools/crud/02spec.php?assn=02cats.php\u0026PHPSESSID=c2840d8b5b59a34e71bd1dac410e4081)\n   - [week4 assignment code](https://github.com/Makiato1999/note-Backend-Django/tree/main/1.%20Django%20Features%20and%20Libraries/catList)\n   - user login\n      ```\n      Account: dj4e_user \n      Password: Meow_7e3398_42\n      ```\n   - dont forget to update admin.py in cats! Otherwise you cannot see its database in admin mode\n   - user login\n      ```\n      Account: casual_user \n      Password: test_uofm_22\n      ```\n7. MySQL\n   - login\n      ```\n      Account:  \n      Password: test_uofm_1999\n      ```\n   - admin\n      ```\n      Account: admin_user\n      Password: admin_uofm_1999\n      ```\n8. Debug, Searching through all your files in the bash shell\n   - If you have errors, you might find the grep tool very helpful in figuring out where you might find your errors.\n      ```\n      cd ~/django_projects/mysite\n      grep -ri myarts *\n      ```\n9. navigation bar and CRUD, profile\n   - [week5 assignment document](https://www.dj4e.com/tools/crud/?PHPSESSID=0f8cbabfd47cfc4b5228c5a8845d724f\u0026PHPSESSID=0f8cbabfd47cfc4b5228c5a8845d724f\u0026url=http%3A%2F%2Fmakiato1999.pythonanywhere.com%2F)\n   - user account and password is also in the assignment document\n1. model and database, many-to-many\u003ca name=\"anchor_64\"\u003e\u003c/a\u003e\n   - it is hard to understand, there is an example, the relationship between books and authors is many-to-many\n   - a book is writen by many authors, and an author can write many books, this is the basic logic\n   - under this condition, for book, author is foreign key. As same logic, for author, book is foreign key \n   - hence, we need a 'through table' set between books and authors, which name is authored\n      - models.py, Book, Author, Authored\n      ```\n      from django.db import models\n      \n      class Book(models.Model):\n         title = models.CharField(max_length = 200)\n         authors = models.MangToManyField('Author', through = 'Authored')\n      \n      class Author(models.Model):\n         name = models.CharField(max_length = 200)\n         books = models.MangToManyField('Book', through = 'Authored')\n         \n      class Authored(models.Model):\n         book = models.ForeignKey(Book, on_delete = models.CASCADE)\n         author = models.ForeignKey(Author, on_delete = models.CASCADE)\n      ```\n    - there is another way to implement many to many relationship, and it looks like dynamic\n      - models.py, Person, Course, Membership\n      ```\n      from django.db import models\n      \n      class Person(models.Model):\n         email = models.CharField(max_length = 128, unique = True)\n         name = models.CharField(max_length = 128, null = True)\n         def __str__(self):\n            return self.email\n      \n      class Course(models.Model):\n         title = models.CharField(max_length = 128, unique = True)\n         members = models.MangToManyField(Person, through = 'Book', through = 'Membership', related_name = 'courses')\n         def __str__(self):\n            return self.title\n            \n      class Membership(models.Model):\n         person = models.ForeignKey(Person, on_delete = models.CASCADE)\n         course = models.ForeignKey(Ccourse, on_delete = models.CASCADE)\n         created_at = models.DateTimeField(auto_now_add = True)\n         updated_at = models.DateTimeField(auto_now = True)\n         \n         LEARNER = 1\n         IA = 1000\n         GSI = 2000\n         INSTRUCTOR = 5000\n         ADMIN = 10000\n         \n         MEMBER_CHOICES = (\n            (LEARNER, 'Learner'),\n            (IA, 'Instructional Assistant'),\n            (GSI, 'Grad Student Instructor'),\n            (INSTRUCTOR, 'Instrucctor'),\n            (ADMIN, 'Administrator '),\n         )\n         \n         role = models.IntegerField(\n            choices = MEMBER_CHOICES,\n            default = LEARNER,\n         )\n         def __str__(self):\n            return \"Person\" + str(self.person.id) + \"\u003c...\u003eCourse\" + str(self.course.id)\n      ```\n   - Indeed there are three ways for creating many-to-many table, django can create table automatically, but use through table would be clear for programming\n      - [实战Django之Model操作之多对多(ManyToMany)正反调用](https://blog.csdn.net/Burgess_zheng/article/details/86594225)\n2. extract information from csv into database by using Django\n   - [week6 assignment document](https://www.dj4e.com/assn/dj4e_load.md?PHPSESSID=e77607e111f0d6cbbba985a07d3a2a38)\n   - [week6 assignment code](https://github.com/Makiato1999/note-Backend-Django/tree/main/1.%20Django%20Features%20and%20Libraries/readCSV)\n## Using JavaScript, JQuery, and JSON in Django\u003ca name=\"anchor_7\"\u003e\u003c/a\u003e\n1. JavaScript\n   - difference between python dictionary and javascript array\n      - they look similar[from google](https://nibes.cn/blog/24300)\n   - first class function\u003ca name=\"anchor_71\"\u003e\u003c/a\u003e\n      - A programming language is said to have First-class functions when functions in that language are treated like any other variable. For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable.\n      - example\n      ```\n      function sayHello() {\n         return \"Hello, \";\n      }\n      \n      function greeting(helloMessage, name) {\n         console.log(helloMessage() + name);\n      }\n      // Pass `sayHello` as an argument to `greeting` function\n      greeting(sayHello, \"JavaScript!\");\n      // Hello, JavaScript!\n      ```\n2. Ads website with nav bar, uploaded pic, comments features\n   - [week2 assignment document](https://www.dj4e.com/assn/dj4e_ads2.md?PHPSESSID=12d4b9da3f5eed4fb4520246b1e81689)\n   - [week2 assignment code](https://github.com/Makiato1999/note-Backend-Django/tree/main/2.%20Using%20JavaScript%2C%20JQuery%2C%20and%20JSON%20in%20Django/Week2-Ads)\n   - admin account is \n      - admin\n      ```\n      Account: admin_user\n      Password: admin_uofm_1999\n      ```\n   - user login\n      ```\n      Account: casual_user \n      Password: test_uofm_22\n      ```\n3. backend flow\n   - ![backend flow with javascript](https://github.com/Makiato1999/note-Backend-Django/blob/main/images/1.png)\n4. jQuery\n   - ID Selector (“#id”), example is below\n     ```\n     \u003cp\u003e\n         \u003ca href=\"#\" id=\"the-href\"\u003eMore\u003c/a\u003e\n     \u003c/p\u003e\n     \u003cul id=the-list\"\"\u003e\n         \u003cli\u003eFirst Item\u003c/li\u003e\n     \u003c/ul\u003e\n     \u003cscript type=\"text/javascript\" src=\"jquery.min.js\"\u003e\u003c/script\u003e\n     \u003cscript\u003e\n     counter = 1;\n     $(document).ready(function(){\n         $(\"#the-href\").on('click', funtion(){\n               console.log('Clicked');\n               $('#the-list').append('\u003cli\u003eThe counter is  '+counter+'\u003c/li\u003e');\n               counter++;\n         });\n     });\n     \u003c/script\u003e\n     ```\n  - difference between ```$(window)``` and ```$(document)```\n      - The window object represents the container that the document object is displayed in. In fact, when you reference document in your code, you are really referencing window.document (all properties and methods of window are global and, as such, can be referenced without actually specifying window at the beginning...)\n      - it's hard to describe, but we can say,\n         - ```document``` can be written as ```window.document```\n         - ```alert()``` can be written as ```window.alert()```\n      - image for easily understanding [image](https://stackoverflow.com/questions/9895202/what-is-the-difference-between-window-screen-and-document-in-javascript#:~:text=window%20is%20the%20root%20of,document%20is%20top%20DOM%20object.)\n5. unique_together\n6. Ads website with nav bar, uploaded pic, comments features, favourite list(only add and delete, can't filter)\n   - [week4 assignment document](https://www.dj4e.com/tools/crud/?PHPSESSID=f014970ff589279c4957d77c9fc451a5)\n   - [week4 assignment code](https://www.dj4e.com/assn/dj4e_ads3.md?PHPSESSID=27e271482bb7d0b118a789c3a52901fe)\n   - admin account is \n      - admin\n      ```\n      Account: admin_user\n      Password: admin_uofm_1999\n      ```\n   - user login\n      ```\n      Account: casual_user \n      Password: test_uofm_22\n      ```\n8. review \n   - object-orientation\n      - [django view object-orientation](https://www.coursera.org/learn/django-javascript-jquery-json/lecture/OoGDt/walkthrough-dj4e-my-articles-myarts-sample-code)\n   - save(commit=False)\n      - [in the form_valid](https://blog.csdn.net/weixin_42134789/article/details/80520500)\n   - request.user.is_authenticated\n   - LoginRequiredMixin\n      - [login/authenticated](https://zhuanlan.zhihu.com/p/40405889)\n   - list[:10]\n9. django-taggit\n1. Ads website with nav bar, uploaded pic, comments features, favourite list(only add and delete, can't filter), search bar, tags\n   - [week5 assignment document](https://www.dj4e.com/assn/dj4e_ads4.md?PHPSESSID=5c6a91001ef8f382471447a8784c8262)\n   - [week5 assignment code]()\n   - admin account is \n      - admin\n      ```\n      Account: admin_user\n      Password: admin_uofm_1999\n      ```\n   - user login\n      ```\n      Account: casual_user \n      Password: test_uofm_22\n      ```\n \n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmakiato1999%2Fbackend-django-notes","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmakiato1999%2Fbackend-django-notes","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmakiato1999%2Fbackend-django-notes/lists"}