Skip to content

Commit 7d5e0f1

Browse files
author
Noah Lloyd-Edelman
committed
Finished models section of Django documentation.
1 parent 600fc41 commit 7d5e0f1

File tree

1 file changed

+115
-22
lines changed

1 file changed

+115
-22
lines changed

django.md

+115-22
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
# Django Notes
22

3+
https://docs.djangoproject.com/en/1.11/
4+
35
Abbreviation | Meaning
46
--- | ---
57
CM | Command
68
PN | Project name
79
AN | Application name
10+
MN | Model name
811
EN | Virtualenv name
912
PR | Project root folder
1013
AR | Application root folder
@@ -13,10 +16,10 @@ AR | Application root folder
1316

1417
command | description
1518
--- | ---
16-
`django-admin <CM>` | These commands can be run anywhere, as long as the `virtualenv` is active.
17-
`python manage.py <CM>` | You must be in the same directory as this file to run it (app root)
19+
`django-admin CM` | These commands can be run anywhere, as long as the `virtualenv` is active.
20+
`python manage.py CM` | You must be in the same directory as this file to run it (app root)
1821

19-
combine with one of the commands below:
22+
combine the above with one of the commands below
2023

2124
command | description
2225
---|----
@@ -30,20 +33,22 @@ dbshell | connects to the database |
3033
cleanup| cleans up the database
3134

3235
### shell_plus commands
36+
3337
command|description
3438
--- | ---
35-
<MN>.objects.all() | Queries all model names and returns the results
36-
<MN>.objects.filter(id=#) | Filter an object's based on an attribute
37-
<MN>.objects.get(pk=#) | get a specific item
38-
q = <MN>(<model_field>="",) | Creates a new model which can be saved using `q.save()`
39+
MN.objects.all() | Queries all model names and returns the results
40+
MN.objects.filter(id=#) | Filter an object's based on an attribute
41+
MN.objects.get(pk=#) | get a specific item
42+
q = MN(<model_field>="",) | Creates a new model which can be saved using `q.save()`
43+
q.add(var), q.create(var), q.set(var) | add = add an object, create = make object, set = add multiple objects
3944
`import datetime` | Useful time management library
4045
`from django.utils import timezone` | Useful timezone conversion library
4146

4247
### Creating an app
4348

4449
Command | What it does
4550
--- | ---
46-
`./manage.py startapp <AN>` | creates an app
51+
`./manage.py startapp AN` | creates an app
4752
`project_root/settings.py` | add the app to `INSTALLED_APPLICATIONS`
4853
`project_root/urls.py` | add the app urls
4954

@@ -57,29 +62,102 @@ Command | What it does
5762
--- | ---
5863
`brew install python3` | Homebrew is a MacOS packager manager
5964
`pip install virtualenv virtualenvwrapper` | installs environment managing tool
60-
`mkvirtualenv <EN>` | create a virtual environment
61-
`workon <EN>` | boot up virtualenv
65+
`mkvirtualenv EN` | create a virtual environment
66+
`workon EN` | boot up virtualenv
6267
`pip install django` | django in the virtualenv
63-
`django-admin startproject <PN>` | creates the base project
68+
`django-admin startproject PN` | creates the base project
6469
`./manage-py runserver` | check if the server runs (must be in project root)
6570

6671
## Application folder
6772

73+
### admin.py
74+
75+
````
76+
from django.contrib import admin
77+
78+
from .models import MN
79+
80+
class MNInline(admin.TabularInline) admin.StackedInline # tabular = large blocks, stackedinline = single row per entry
81+
model = MN
82+
extra = #
83+
84+
class MNAdmin(admin.ModelAdmin):
85+
fieldset = [
86+
(<title>, {'fields': ['field', 'field']}),
87+
(<title>, {'fields': ['field', 'field']}),
88+
]
89+
inlines = [MNInline] # Add outside model as inline
90+
list_display = ('field', 'field', 'model_function') # columns to display for models
91+
list_filter = ['field'] # sidebar filter
92+
search_fields = ['field'] # searchbox for field
93+
94+
admin.site.register(MN, MNAdmin)
95+
````
96+
6897
### models.py
6998

99+
https://docs.djangoproject.com/en/1.11/topics/db/examples/
100+
70101
````
71102
from django.db import models
72103
73104
74-
class <ClassName>(models.Model):
75-
var = models.CharField(max_length=5, default='aaa')
76-
foreign_key = models.ForeignKey(<target_model>, on_delete=cascade)
77-
105+
class ClassName(models.Model):
106+
SOME_CHOICES = (
107+
('X', 'XX'),
108+
('Y', 'YY'),
109+
('Z', 'ZZ'),
110+
)
111+
# L side goes into database / R for readability
112+
# get_SOME_CHOICES_display() to show 2nd value
113+
114+
var = models.CharField(
115+
"verbose name for field",
116+
max_length=5,
117+
default='aaa',
118+
blank=True,
119+
help_text='ahhhhhh',
120+
unique=True,
121+
)
122+
var1 = models.CharField(
123+
max_length=1,
124+
choices=SOME_CHOICES
125+
)
126+
foreign_key = models.ForeignKey(
127+
<target_model>,
128+
on_delete=models.CASCADE,
129+
verbose_name='a related something',
130+
)
131+
many_to_many = models.ManyToManyField(<target_model>)
132+
many_to_many = models.ManyToManyField(
133+
<target_model>,
134+
through='Intermediate table',
135+
)
136+
137+
class Meta:
138+
ordering = ['var']
139+
verbose_name_plural = 'things'
140+
78141
__str__(self)
79142
return self.var
80-
143+
81144
def some_function(self):
82145
return self.somevar == timezone.now()
146+
147+
def get_absolute_url(self):
148+
from django.urls import reverse
149+
return reverse('model.views.view_name', args=[str(self.id)])
150+
151+
# Abstract base model w/ child model
152+
class AbstractBaseModel(models.Model):
153+
var = models.CharField(max_length=1)
154+
155+
class Meta:
156+
abstract = true
157+
158+
class AbstractChildModel(AbstractBaseModel):
159+
var = models.CharField(max_length=1)
160+
83161
````
84162

85163
### urls.py
@@ -91,16 +169,31 @@ from . import views
91169
92170
urlpatterns = [
93171
url(r'^$', views.index, name='index'),
172+
url(r'(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='details'),
94173
]
95174
````
96175

97176
### views.py
98177

99178
````
100179
from django.http import HttpResponse
180+
from django.view import generic
101181
102182
def index(request):
103183
return HttpResponse("Hello.")
184+
185+
def DetailView(generic.DetailView):
186+
model = MN
187+
template_name = 'AN/templates/AN/<file>.html'
188+
189+
def get_queryset(self):
190+
return MN.objects.filter(name='?')
191+
````
192+
193+
### *.html
194+
195+
````
196+
<a href="{{ object.get_absolute_url }}">{{ object.name }}</a>
104197
````
105198

106199
## Project folder
@@ -114,11 +207,11 @@ from django.http import HttpResponseRedirect
114207
115208
urlpatterns = [
116209
# e.g. myapp/
117-
url(r'^<AN>/', include(<AN>.urls')),
210+
url(r'^AN/', include(AN.urls')),
118211
# e.g. admin/
119212
url(r'^admin/', admin.site.urls),
120213
# e.g. /
121-
url(r'^$', lambda r: HttpResponseRedirect('<AN>/')),
214+
url(r'^$', lambda r: HttpResponseRedirect('AN/')),
122215
]
123216
````
124217

@@ -127,7 +220,7 @@ urlpatterns = [
127220
````
128221
INSTALLED_APPS = [
129222
'django_extensions',
130-
'<AN>.apps.<AN>Config',
223+
'AN.apps.ANConfig',
131224
'django.contrib.admin',
132225
'django.contrib.auth',
133226
'django.contrib.contenttypes',
@@ -137,10 +230,10 @@ INSTALLED_APPS = [
137230
]
138231
````
139232

140-
141233
## Webstorm
142234

143235
### Setting up a server script
236+
144237
`Languages > Frameworks > Django` - check enable django support
145-
The settings file is in `<PR>/<PF>/settings.py`
146-
You can edit your configurations in the top right. I recommend giving them names and only allowing single instances to run.
238+
The settings file is in `PR/PF/settings.py`
239+
You can edit your configurations in the top right. I recommend giving them names and only allowing single instances to run.

0 commit comments

Comments
 (0)