Assignment 2: Django
  • Due date: Fri February 25, 2022 23:59:00
  • remaining
Objectives

In this assignment, you will create a small Django application. Since it's an educational assignment, many details and nuances have been simplified for you. For example, the overall app structure, views, and URLs will be set out for you in this handout. The overall goal is to obtain an initial experience at backend development and Django so that you will be prepared for Project phase 2.

Note that even though what was taught in the lectures is enough "knowledge" to cover this assignment, it's quite possible that some specific views, functions, and tricks are not covered in the lectures. There are millions of features in web programming, and it's really impossible to teach them all in a lecture.

Therefore, you are welcome to refer to the slides or online resources to lookup for specific things. However, please be mindful that you will not violate academic integrity, as explained later on.

Notes
  • This assignment will make up 15% of your final grade.
  • The due date is Friday, February 25th at 23:59:00. Late submissions will incur a 15% penalty per day for a maximum of 3 days.
  • If you have any questions or problems with the assignment, please post them on Piazza.
  • Your submissions will be mostly auto-graded. Therefore, your code must adhere to all details provided in the handout; otherwise, you might lose marks.
  • You will not receive any feedback from the auto grader before the deadline has passed. So it is your responsibility to double-check your code with the handout before submission. Even minor spelling mistakes can lead to loss of marks. No remark requests will be accepted on these matters.
Submission

You should submit your work to your git repository on Markus. That is, you cannot submit through its normal web interface. Instead, commit and push your codes to your repository and the corresponding folder for assignment 2. Find out your repo's URL by logging into Markus. Also, do not leave your commits to the final minutes before the deadline.

Academic Integrity

Assignments are individual work which means that you will not be allowed to seek advice from other students or copy/paste someone else's code, even open-source codes from the internet. However, you are allowed to look at online resources, tutorials, and Q&A websites over the course of solving the problems. The entire code must be written by yourself.

What to submit

You must push your entire Django project to your repo. That includes migrations files, manage.py, and templates. Do not push your database (db.sqlite3) or virtual environment, as the tester will ignore them. Instead, put those on the gitignore file.

Please carefully follow the instructions in the upcoming sections on creating the Django project, the list of apps, and what packages to install. Also, do not change any default configuration at settings.py (except for INSTALLED_APPS and ALLOWED_HOSTS that are described later on) as it may confuse the tester.

Please be very careful that you exactly copy/paste the error messages, URLs, and field names. The auto tester will look for the exact matches, and even slight mis-spellings or lowercase/uppercase problems will lead to loss of marks. This time, no exceptions will be considered. For your help, copy buttons are attached to long error messages and URLs. However, they do not indicate the complete list of strings that must exactly match the handout.

Warning: The tester runs your code in a clean environment. So it's crucial to make sure that your migrations are correct and runnable. You can move your database file to another folder and run ./manage.py migrate to check if it works. If your migrations don't work or your server fails to start, the auto tester will not be able to test your code, and you will not get any marks.

Virtual machine

A virtual machine has already been offered to you. It is the environment in which the auto tester will run your code. So, to avoid unexpected issues, you are advised to use that environment to run your code. However, you are allowed to work on other operating systems and environments as well, but at your own risk. It is crucially important for you to at least double-check your whole project in that virtual machine before submitting it. Therefore, if, for any reason, your code does not run, you will not get any marks.

Important Note: If you downloaded the virtual machine before Feb. 15th, make sure you read instructions listed here to install additional packages. Moreover, to access your website, you might need to modify ALLOWED_HOSTS in settings.py. More information can be found here at the bottom of the page.

Pre-tester

For your help, a pre-tester is given to you that runs some basic checks on your project. For example, it checks the endpoints and sends some simple requests to them. Before submitting, you might want to run the pre-tests and make sure that all of them pass. However, note that the pre-tests include a very small set of test cases, and passing them will not guarantee full or even partial marks at final tests. They are only provided to you to avoid losing marks because of simple differences in endpoints or fields. However, you are still responsible for making sure that all your endpoints, fields, and error messages exactly match the handout. You can find the instructions on running the pre-tests here.

Creating the project

Create a virtual environment with Python 3.8, 3.9, or 3.10. Only install Django version 4.0.1 or 4.0.2 in your environment. It is the only package the auto tester will install, and your code will not run if you have used other external packages.

Follow the instructions from the lectures to create a Django project named a2 (lowercase). Create two apps: accounts and banks. Do not forget to append the app names to INSTALLED_APPS at settings.py. You are to create two models: Bank and Branch.

A bank has a name, swift code, institution number, and description. All of them are strings that do not exceed 200 characters and cannot be null. Moreover, each bank has an owner that points to Django's User model. A bank also has a set of branches.

A branch has a name, transit number, and address, all of which are strings that do not exceed 200 characters and cannot be null. Moreover, every branch has an email (with its specific validations) which is by default set to admin@utoronto.ca . Each branch has a capacity (non-negative integer) that could be left unspecified. It should also have last_modified, a field that stores the last modification time. The primary key for both models must remain the default auto-incrementing integers.

General note on forms

For every endpoint, every time a URL is associated with both GET and POST, the following rule applies: The GET request expects an HTML form with the fields listed by the payload. That is, each payload field must appear as an <input> with the appropriate type and name.

Upon submission, a POST request should be sent to the same endpoint. If data is valid, the specific task should be fulfilled, and the user is redirected to the success URL. Otherwise, the same form must be rendered with relevant error messages listed in validation errors. Note that all user inputs (except for password) must be preserved so that the user will not have to re-enter everything again.

Furthermore, input types must adhere to the original field type of their models. For example, the password fields should be rendered with <input type="password">; email fields should be rendered <input type="email"> and so on. However, note that this (or adding the required attribute to the form) is merely for UX purposes and has nothing to do with your backend. That is, your backend code must still check for the required fields and validations.

Note: Your code must be resilient to invalid/malicious requests. For example, the client might intentionally discard some fields and not send them (note that this is different from sending empty or blank values). Moreover, it can send additional fields that are not listed. In either case, your code must not break. That is, the server should not return a 500 INTERNAL SERVER ERROR. Instead, it should treat missing values as blanks and ignore extra fields.

HTTP status codes

All requests should be responded to with an HTTP 200 OK status code unless otherwise specified. In case of redirects, your status code must be 302 FOUND. You must check for client errors in the following order: 401 UNAUTHORIZED, 404 NOT FOUND, and 403 FORBIDDEN. That is, for example, at the create branch view, if the request is not authenticated and the bank ID is invalid as well, you should return 401 UNAUTHORIZED. Your server must never return a 500 INTERNAL SERVER ERROR.


As simple as Auth!

You will start off with the authentication views. You are to implement views for register, login, and logout. You are very well allowed to use the default User model in Django. In fact, you are strongly advised against creating your own custom auth model as it may mess with Django's default User model. Moreover, why bother yourselves?

In this question, you are allowed to use function-based, class-based views, or generic CRUD views. You can also use any built-in tool that is already provided by Django.

  • Endpoint: /accounts/register/
    Methods: GET, POST
    Fields/payload: username, password1, password2, email, first_name, last_name
    Success URL: /accounts/login/
    Validation errors: (copy and paste the exact error message)
    • The two password fields didn't match
    • A user with that username already exists
    • This password is too short. It must contain at least 8 characters
    • Enter a valid email address
    • Username, password, and repeat password are required. If empty, show the following error above the problematic field:
      This field is required
    Additional notes: In our tests, no field will be more than 120 characters long.

  • Endpoint: /accounts/login/
    Methods: GET, POST
    Fields/payload: username, password
    Success URL: /accounts/profile/view/
    Invalid inputs: (copy and paste the exact error message)
    • Username or password is invalid
    Additional notes: If the credentials are valid, use Django's session authentication to log the user in.

  • Endpoint: /accounts/logout/
    Methods: GET
    Description: Log the user's session out of Django. If the user is unauthenticated, simply ignore the request. In either case, return a redirect to /accounts/login

Profilers

In this question, you will implement the view and edit profile functionalities. Note that you should return HTTP 401 UNAUTHORIZED if the request is unauthenticated.

  • Endpoint: /accounts/profile/view/
    Methods: GET
    Fields: id, username, email, first_name, last_name
    Description: Return a JSON string with the above fields, disclosing data on the logged-in user.
    Example response:
    {"id": 1, "username": "Demon", "email": "demon@gmail.com", "first_name": "", "last_name": ""}

  • Endpoint: /accounts/profile/edit/
    Methods: GET, POST
    Fields/payload: first_name, last_name, email, password1, password2
    Success URL: /accounts/profile/view/
    Validation errors: (copy and paste the exact error message)
    • The two password fields didn't match
    • This password is too short. It must contain at least 8 characters
    • Enter a valid email address
    Additional notes: At GET requests, the form (except for the password fields) must be already filled out with the current user's values. At the POST request, if password1 is empty, it means that the user did not want to change its password. Therefore, password2 should be ignored, and no changes will be made to the user's password.

If you know forms, you know.

Now, let's move to the banks app. You will implement two important forms; one for creating a new bank and another one for creating a new branch. Note that, in this question, you are not allowed to use function-based views. Instead, your views must be subclasses of FormView. Moreover, you should create a forms directory in your app and put a Form (or ModelForm) class for each view there. If you do not follow that rule, you will not get any marks for this question.

Moreover, the below views are login required. If the request is unauthenticated, a 401 UNAUTHORIZED response must be returned.

  • Endpoint: /banks/add/
    Methods: GET, POST
    Fields/payload: name, description, inst_num, swift_code
    Success URL: /banks/<bank_id>/details/
    Validation error: All fields are mandatory and cannot be left blank. If so, the following error must be shown above the problematic field:
    • This field is required
    Additional notes: Your code must infer the owner of the new account from the current user logged in to the session. Therefore, you must not include an owner field in your form. Moreover, bank_id is the ID of the newly-created bank.

  • Endpoint: /banks/<bank_id>/branches/add/
    Methods: GET, POST
    Fields/payload: name, transit_num, address, email, capacity
    Success URL: /banks/branch/<branch_id>/details/
    Validation errors:
    • This field is required
      (for all fields except for capacity)
    • Enter a valid email address
    Additional notes:
    • The bank to which the new branch belongs must be fetched using bank_id from the URL args. If no bank exists with such an ID, both GET and POST should return 404 NOT FOUND.
    • The user must be the owner of the corresponding bank; otherwise, a 403 FORBIDDEN must be returned (both GET and POST). In other words, users must not be able to add a branch to someone else's bank.
    • The branch_id in the success URL is the ID of the newly-created branch.

JSON is all you ever need

In this question, you will create two views that return JSON responses. One of them returns the info of a specific branch, and the other returns all branches belonging to a specific bank. Note that these views should be accessible by everyone, even unauthenticated requests. Also, if the given ID is not associated with any bank or branch, you should return a 404 NOT FOUND response.

  • Endpoint: /banks/branch/<branch_id>/details/
    Methods: GET
    Fields:
    id, name, transit_num, address, email, capacity, last_modified
    Example response:
    {"id": 1, "name": "jkl", "transit_num": "12", "address": "jlk", "email": "admin@utoronto.ca", "capacity": 12, "last_modified": "2022-01-08T22:30:40.419Z"}


  • Endpoint: /banks/<bank_id>/branches/all/
    Methods: GET
    Fields:
    id, name, transit_num, address, email, capacity, last_modified
    Example response:
    [{"id": 1, "name": "jkl", "transit_num": "12", "address": "jlk", "email": "admin@utoronto.ca", "capacity": 12, "last_modified": "2022-01-08T22:30:40.419Z"}]


Wrong Crawd!

Finally, it's time for some generic views. You are only allowed to use the specified class for each endpoint. The views entail reading or modification of a model object.

  • Endpoint: /banks/all/
    Methods: GET
    View class: ListView
    Authenticated: NO
    Description: An HTML response must be returned that lists all banks. The page should show the ID and the name of each bank in an ordered or unordered list.

  • Endpoint: /banks/<bank_id>/details/
    Methods: GET
    View class: DetailView
    Authenticated: NO
    Description: An HTML response must be returned that contains the information of a specific bank (or a 404 NOT FOUND if it does not exist). The information to be shown are the bank name (wrapped by an <h1>), its swift code, institution number, and description.

  • Endpoint: /banks/branch/<branch_id>/edit/
    Methods: GET, POST
    View class: UpdateView
    Authenticated: YES (return 401 UNAUTHORIZED otherwise)
    Fields/payload: name, transit_num, address, email, capacity
    Success URL: /banks/branch/<branch_id>/details/
    Validation errors:
    • This field is required
      (for all fields except for capacity)
    • Enter a valid email address
    Additional notes: The form must be pre-filled with the current values of the branch instance. Moreover, the branch's bank is not changeable; hence it should not be a part of the form. The user must be the owner of the corresponding bank; otherwise, a 403 FORBIDDEN response must be returned (both GET and POST). In other words, users must not be able to modify someone else's branches.

Comments

  • This is my fourth time taking CSC309, and inarguably, this is the best assignment I've ever seen.
    Problems are so accurately designed that anyone with their own knowledge and experience have their own takeaways.
    I hope next assignments will be this good, too!

    • Thanks bro!

Write a comment
Your email address will not be published. Required fields are marked *
Review*
Name*
Email*
Notify me of new posts by email