-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdjango
146 lines (109 loc) · 4.72 KB
/
django
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
django notes:
# To rebuild table after deleting migrations
https://stackoverflow.com/questions/33259477/table-was-deleted-how-can-i-make-django-recreate-it
### Activate Virtual Environment First ###
# To start a new project from the parent directory of where the project will live:
django-admin.py startproject <project_name>
# To create a new app underneath an existing project
python manage.py startapp hello_world
# To add the app to the project
vi hello_world_project/settings.py
# Inside the 'INSTALLED_APPS' tuple add 'hello_world'
# To run the development server and accept connections from any host:
python manage.py runserver 0.0.0.0:8000
### To create a superuser ###
python manage.py createsuperuser
### Update Database Models ###
1. Update the models
2. Create your migrations 'python manage.py makemigrations'
3. Apply the migrations 'python manage.py migrate'
### To work with DB objects ###
# http://tutorial.djangogirls.org/en/django_orm/
python manage.py shell # This gets into the django shell, if you want to quickly test
from my_app.models import MyDBModel
MyDBModel.objects.all() # To retrieve all objects in a model
# To retrieve a specific object
me = User.objects.get(username='myuser')
# This is to add in a new object referencing another object 'me'
MyDBModel.objects.create(author = me, field1='foo', field2='bar')
# Filter Query on specific match
MyDBModel.objects.filter(author=myuser)
# Filter using contains, less then, great then, great then equal to, etc
# gt, lt, gte, lte (field1__lte=100)
MyDBModel.objects.filter(field1__contains='mysearchtext')
# Ordering DB objects
MyDBObject.objects.order_by('created_date') # ascending
MyDBObject.objects.order_by('-created_date') # descending, notice the dash prefix
# Chaining QuerySets
MyDBObject.objects.filter(author='myuser').order_by('created_date')
### Function Based View Examples ###
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
from django.shortcuts import render, redirect, get_object_or_404
from customer.models import Customer
from customer.forms import CustomerForm
@login_required()
def customer_model_list_view(request):
queryset_list = Customer.objects.order_by('name')
query = request.GET.get("q")
if query:
queryset_list = queryset_list.filter(
Q(name__icontains=query) |
Q(telephone__icontains=query) |
Q(email__icontains=query)
).distinct() # this prevents duplicates
for customer in queryset_list:
customer.telephone = "({}) {}-{}".format(customer.telephone[:3], customer.telephone[3:6], customer.telephone[6:])
paginator = Paginator(queryset_list, 10)
page = request.GET.get('page')
try:
queryset = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
queryset = paginator.page(1)
except EmptyPage:
# If page is out of range, deliver last page of results.
queryset = paginator.page(paginator.num_pages)
context = {'object_list': queryset}
return render(request, 'customer/customer_list.html', context)
@login_required()
def customer_model_create_view(request):
form = CustomerForm(request.POST or None)
if form.is_valid():
obj = form.save(commit=False)
# make modifications here
form.save()
messages.success(request, "Customer was created successfully!")
return redirect('customer_app:detail', pk=obj.pk)
return render(request, 'customer/customer_create.html', {'form': form})
@login_required()
def customer_model_update_view(request, pk=None):
obj = get_object_or_404(Customer, pk=pk)
form = CustomerForm(request.POST or None, instance=obj)
if form.is_valid():
obj = form.save(commit=False)
# make modifications here
form.save()
messages.success(request, "Customer was updated successfully!")
return redirect('customer_app:detail', pk=obj.pk)
return render(request, 'customer/customer_create.html', {'form': form})
@login_required()
def customer_model_detail_view(request, pk=None):
obj = get_object_or_404(Customer, pk=pk)
context = {
"object": obj,
}
return render(request, 'customer/customer_detail.html', context)
@login_required()
def customer_model_delete_view(request, pk=None):
obj = get_object_or_404(Customer, pk=pk)
if request.method == "POST":
obj.delete()
messages.success(request, "Customer was deleted successfully!")
return redirect('customer_app:list')
context = {
"object": obj,
}
return render(request, 'customer/customer_delete.html', context)