- Model - Data Access Layer
- Data Objects for the database(ORM)
- Template - Presentation Layer
- What The User Sees
- View - Business Logic
- Urls Send HTTPResponse
- Views REspond with HTTP Request
- wsgi.py - webserver gateway interface - actual server
- urls.py - url routing to project
- project urls.py use
include
function fromdjango.urls
to inlclude the urls.py file for an application - if there are id endpoints, that must be passed to the view as a paramenter
- project urls.py use
- asgi - asynchronous calls
- settings.py - core project ocnfiguration regarding app installs, urls formatting,database formatting, etc
- Update application definitions in
INSTALLED_APPS
for example,base.apps.BaseConfig
messages = Message.objects.create( user=request.user, room=room, body=request.POST.get('body') )
- Update application definitions in
views.py
- where your application views go- use render to render templates to views
- On saving models you can use form save or the create option for the model 1.
apps.py
- provides application configuration- app will have its own views that are passed here from
base.views.View
- app will have its own views that are passed here from
urls.py
- where your url patterns for the app resides, configuration endpoint with viewspath('room/<str:pk>/', views.room, name="room")
-- name allows us to change the path without updating the template. use name when loading url href. ex."{% url 'user-profile' room.host.id %}"
models.py
- where your orm for django database will reside- Datatypes
CharField(max_length=200)
TextField(null=True, blank=True)
DateTimeField(auto_now=True)
- auto updates date field on textauto_now_add=True
- timestamp set when created
models.ForeignKey(Room, on_delete=models.CASCADE)
- adding a foreign key for a many to one relationship established by child model- you can query the foreign key that is connected to the object you query
- can fetch set of child as follows:
messages = Room.message_set.all()
- Datatypes
admin.py
- where you register your models to site so you can view it in admin dashboardforms.py
- similar to django serializers, you create meta and specify fields- create user creation form that overrides forms or inherits from them. These can be imported into your views
- Where your template directory is for your html/css
- Make sure to update
TEMPLATES
configuration in projectsettings.py
- Make sure to update
- Template Inheritence
- create a html template and then use include to use it on other html pages
{% include 'navbar.html' %}
- Split divs into component htmls that can be included in other page content
- main.html where common includes exist
{% extends 'main.html' %}
- create a html template and then use include to use it on other html pages
- App templates
- Must create template folder/{name of app} - required
- specify app folder in template in
render(request, 'base/home.html', {'rooms': rooms})
- specify app folder in template in
- Must create template folder/{name of app} - required
- Main templates
- reusuable stuff for project that are extended in app templates
- Block content
- create common content in main.html and use the block content specifically to add items in relation for your page or child content
{{request.META.HTTP_REFERER}}
- redirects to where they came from
- variables - two curly braces,
{{}}
- Tags - loops, logic, filters. csrf_token
{%%}
{{% for x in render_variable %}}
- Can pass variables using render function
render(request, 'home.html', {'rooms': rooms})
- Concatenate url
"{% url 'delete-room' room.id %}"
- Query URL
"{% url 'home' %}?q={{topic.name}}"
- Query filter requires input
- View requires the following
q = request.GET.get('q') if request.GET.get('q') != None else ''
rooms = Room.objects.filter(
Q(topic__name__icontains=q) |
Q(name__icontains=q) |
Q(description__icontains=q))
<form method="GET" action="{% url 'home' %}">
<input type="text" name="q" placeholder="Search Rooms..."/>
</form>
<a href="{% url 'home' %}?q={{topic.name}}">{{topic.name}}</a>
django-admin
- shows subcommandsdjango-admin startproject <name_of_project>
- creates projectpython manage.py startapp <name_of_app>
- creates applicationpython manage.py runserver
- runs applicationpython manage.py makemigrations
- when changes are made to model or view (stages migrations)python manage.py migrate
- migrate changes- builds database for us
python manage.py createsuperuser
- creates superuser
- Create a Model
- Migrate the model
- Create response views which can be either views, view templates, or functional views
- Specify urls that match response view function requirements
- id will have id parameter for response
- Create template for the view at application level
- leverage template inheritence and ability to pass context from render
- Django built in session
- Navigate to chrome console and go to
application->cookies
to view session - Do not call login view as login as it is a function in django
from django.contrib.auth.decorators import login_required
if user is not logged in add this decorator- Steps completed
- Create login and logout page and views
- Check if authenticated in both views and templates
- Show info or template componants based on auth status
- redirect when user is authenticated or if user requires auth for that page
- use context for login and registration options
- Steps completed
- Create POST options to get inputs for messages
- Haven't complted
- Option to edit messages
from django.contrib import messages
https://docs.djangoproject.com/en/4.0/ref/contrib/messages/
- Like Templates create root static files with styles and image folder
- Create a variable
STATICFILES_DIRS = [BASE_DIR / 'static']
in settings.json - load static using following:
{% load static %}
and must be set for each main template html page to use static folder. everything else will be configured viablock content
- reference stylesheet similar to url and template
<link rel="stylesheet" type='text/css' media='screen' href="{% static 'styles/main.css' %}">
- To add images
<img src="{% static 'images/image.png' %}">
- To add user upload images
<div class="form__group">
<label for="room_topic">Enter a Topic</label>
{% comment %} List topic for dropdown which must match datalist id {% endcomment %}
<input required name="topic" type="text" value="{{room.topic.name}}" list="topic-list" />
<datalist id="topic-list">
<select id="room_topic">
{% for topic in topics %}
<option value="{{topic.name}}">{{topic.name}}</option>
{% endfor %}
</select>
</datalist>
</div>
- Can create a new application or a new folder in existing app called
api
which includesviews.py
-__init__.py
urls.py
- api paths that are added to project urlsserializers.py
- similar to model form
pip install djangorestframework
and addrest_framework
tosettings.json
of project
- PIP install pillow
<form class="form" method="POST" action="" enctype="multipart/form-data">
- enctype must be specified to upload imageform = UserForm(request.POST, request.FILES, instance=user)
- request files from image