Created
June 11, 2016 19:05
-
-
Save SivaCse/04a31f889d3502e43209fc4020cf422f to your computer and use it in GitHub Desktop.
Django Development time helper notes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
kill port already defined | |
========================= | |
fuser -k 8000/tcp | |
Kill annd Restart whenever u added new apps | |
--------------------------------------------- | |
Create and activate virtual environment | |
======================================== | |
pip install virtualenv | |
pip freeze | |
virtualenv ecitvenv | |
[root@ws26 ecitvenv]# source bin/activate | |
---------------------------------------------- | |
Creating a project | |
================== | |
django-admin startproject projectname | |
-------------------------------------- | |
run command | |
=========== | |
python manage.py runserver 8001 | |
python manage.py runserver 103.231.43.193:9000 | |
--------------------------- | |
Create app | |
========== | |
python manage.py startapp appname | |
-------------------------------- | |
Import a package | |
================ | |
from django.http import HttpResponse | |
from . import views | |
-------------------------------- | |
url settings | |
============ | |
from django.conf.urls import url | |
from . import views | |
urlpatterns = [ | |
url(r'^$', views.index, name='index'), | |
] | |
------------------------- | |
include url | |
=========== | |
from django.conf.urls import include, url | |
from . import views // views module from current app | |
urlpatterns = [ | |
url(r'^polls/', include('polls.urls')), | |
url(r'^$', views.index, name='index'), // for example home page | |
url(r'^(?P<pkcolumn>[0-9]+)/$', views.detail, name='detail'), // ex: /polls/5/ | |
url(r'^(?P<pkcolumn>[0-9]+)/results/$', views.results, name='results'), // /polls/5/results/ | |
] | |
---------------------------------------- | |
Database settings | |
================= | |
DATABASES = { | |
'default': { | |
'ENGINE': 'django.db.backends.mysql', | |
'NAME': 'eaglesoft', | |
'USER': 'siva', | |
'PASSWORD' : 'siva098' | |
} | |
} | |
--------------------------------- | |
migrations command | |
================== | |
python manage.py migrate | |
python manage.py makemigrations then use above command if model modified | |
Install an app in settings | |
========================== | |
INSTALLED_APPS = [ | |
... | |
'customer', | |
'salesperson', | |
'serviceprovider', | |
... | |
] | |
-------------------------------- | |
Create a model | |
============== | |
from django.db import models | |
class Question(models.Model): | |
fields | |
-------------------------------- | |
Create a foriegn key relationship | |
================================= | |
class Choice(models.Model): | |
question = models.ForeignKey(Question, on_delete=models.CASCADE) | |
--------------------------------- | |
Open shell prompt | |
================= | |
python manage.py shell | |
------------------------ | |
add current time in database field while saving | |
=============================================== | |
from django.utils import timezone | |
q = Question(question_text="What's new?", pub_date=timezone.now()) | |
------------------------------------------------ | |
get primary key after saving | |
============================ | |
q.save() | |
q.id // saved pk | |
---------------------------- | |
fetch all model data | |
==================== | |
Question.objects.all() | |
-------------------------- | |
String representation of model for easy view and learning | |
========================================================= | |
class Question(models.Model): | |
def __str__(self): | |
return self.question_text | |
--------------------------------------------------------- | |
Create custom function in model | |
=============================== | |
class User(models.Model): | |
def fullname(self): | |
return self.first_name + self.last_name | |
------------------------------------ | |
Filter a model based attribute | |
============================== | |
Question.objects.filter(id=1) | |
Question.objects.filter(question_text__startswith='What') | |
Question.objects.get(pk=1) | |
------------------------------- | |
Call custom function of a model | |
=============================== | |
q = User.objects.get(pk=1) | |
q.fullname() | |
-------------------------------- | |
Fetch related model data | |
======================== | |
q = Question.objects.get(pk=1) | |
q.choice_set.all() | |
----------------------------- | |
Save related models at a time | |
============================= | |
q = Question(question_text="What's new?", pub_date=timezone.now()) | |
q.save() | |
q.choice_set.create(choice_text='Not much', votes=0) | |
q.choice_set.count() // get count | |
q.delete() // for delete | |
-------------------------------------- | |
Creating an admin user | |
====================== | |
python manage.py createsuperuser | |
------------------------------------ | |
Show the apps model in admin backend | |
==================================== | |
in appsdirectory/admin.py | |
from django.contrib import admin | |
from .models import Question | |
admin.site.register(Question) | |
-------------------------------------- | |
Model order by fetching | |
======================= | |
from django.http import HttpResponse | |
from .models import Question | |
def index(request): | |
latest_question_list = Question.objects.order_by('-pub_date')[:5] | |
output = ', '.join([q.question_text for q in latest_question_list]) | |
return HttpResponse(output) | |
it can be accessed in template like below, | |
polls/templates/polls/index.html | |
{% if latest_question_list %} | |
<ul> | |
{% for question in latest_question_list %} | |
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> | |
{% endfor %} | |
</ul> | |
{% else %} | |
<p>No polls are available.</p> | |
{% endif %} | |
-------------------------------------------- | |
Exception and Raising a 404 error | |
================================= | |
from django.http import Http404 | |
from django.shortcuts import render | |
from .models import Question | |
def detail(request, question_id): | |
try: | |
question = Question.objects.get(pk=question_id) | |
except Question.DoesNotExist: | |
raise Http404("Question does not exist") | |
return render(request, 'polls/detail.html', {'question': question}) | |
in polls/templates/polls/detail.html | |
{{ question }} | |
Alternative method | |
from django.shortcuts import get_object_or_404, render | |
from .models import Question | |
def detail(request, question_id): | |
question = get_object_or_404(Question, pk=question_id) | |
return render(request, 'polls/detail.html', {'question': question}) | |
--------------------------------------------------------------------------- | |
Using for loop in views | |
======================== | |
<h1>{{ question.question_text }}</h1> | |
<ul> | |
{% for choice in question.choice_set.all %} | |
<li>{{ choice.choice_text }}</li> | |
{% endfor %} | |
</ul> | |
---------------------------------------------- | |
Url link to show view by passing pkey | |
===================================== | |
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> | |
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li> | |
set app name | |
app_name = 'polls' | |
urlpatterns = [ | |
url(r'^$', views.index, name='index'), | |
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), | |
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'), | |
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), | |
] | |
then | |
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> | |
---------------------------------------------------------------------------------- | |
Write a simple form | |
=================== | |
polls/templates/polls/detail.html | |
<h1>{{ question.question_text }}</h1> | |
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} | |
<form action="{% url 'polls:vote' question.id %}" method="post"> | |
{% csrf_token %} | |
{% for choice in question.choice_set.all %} | |
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> | |
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> | |
{% endfor %} | |
<input type="submit" value="Vote" /> | |
</form> | |
url for generic views | |
===================== | |
urlpatterns = [ | |
url(r'^$', views.IndexView.as_view(), name='index'), | |
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), | |
url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'), | |
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), | |
] | |
------------------------------------------------ | |
Generic view custom query set | |
============================= | |
class IndexView(generic.ListView): | |
template_name = 'polls/index.html' | |
context_object_name = 'latest_question_list' | |
def get_queryset(self): | |
"""Return the last five published questions.""" | |
return Question.objects.order_by('-pub_date')[:5] | |
------------------------------------------------- | |
Adding static files ( css , js , image ) into our app's template | |
================================================================ | |
polls/static/polls/style.css | |
{% load static %} | |
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" /> | |
model object to string for learning | |
=================================== | |
def __str__(self): | |
return self.status_desc | |
----------------------------------- | |
Create custom permission example | |
================================ | |
class Task(models.Model): | |
... | |
class Meta: | |
permissions = ( | |
("view_task", "Can see available tasks"), | |
("change_task_status", "Can change the status of tasks"), | |
("close_task", "Can remove a task by setting its status as closed"), | |
) | |
--------------------------------- | |
Check user has a permission | |
=========================== | |
user.has_perm('app.view_task') | |
----------------------------- | |
Block of content inside a template | |
=================================== | |
{% extends "base.html" %} | |
{% block content %} | |
<h2>Publishers</h2> | |
<ul> | |
{% for publisher in object_list %} | |
<li>{{ publisher.name }}</li> | |
{% endfor %} | |
</ul> | |
{% endblock %} | |
------------------------------------- | |
Generic view custom query | |
========================= | |
from django.views.generic import ListView | |
from books.models import Book | |
class BookList(ListView): | |
queryset = Book.objects.order_by('-publication_date') | |
------------------------------------------ | |
Filter based current user in generic view | |
========================================= | |
from django.shortcuts import get_object_or_404 | |
from django.views.generic import ListView | |
from books.models import Book, Publisher | |
class PublisherBookList(ListView): | |
template_name = 'books/books_by_publisher.html' | |
def get_queryset(self): | |
self.publisher = get_object_or_404(Publisher, name=self.args[0]) | |
return Book.objects.filter(publisher=self.request.user) | |
--------------------------------------------- | |
URL Redirection after delete | |
======================== | |
class AuthorDelete(DeleteView): | |
model = Author | |
success_url = reverse_lazy('author-list') | |
------------------------------------------------ | |
fetch objects that are created by specific user | |
=============================================== | |
from django.contrib.auth.models import User | |
from django.db import models | |
class Author(models.Model): | |
name = models.CharField(max_length=200) | |
created_by = models.ForeignKey(User, on_delete=models.CASCADE) | |
from django.views.generic.edit import CreateView | |
from myapp.models import Author | |
class AuthorCreate(CreateView): | |
model = Author | |
fields = ['name'] | |
def form_valid(self, form): | |
form.instance.created_by = self.request.user | |
return super(AuthorCreate, self).form_valid(form) | |
--------------------------------------------------- | |
CreateView with ajax example | |
============================ | |
from django.http import JsonResponse | |
from django.views.generic.edit import CreateView | |
from myapp.models import Author | |
class AjaxableResponseMixin(object): | |
""" | |
Mixin to add AJAX support to a form. | |
Must be used with an object-based FormView (e.g. CreateView) | |
""" | |
def form_invalid(self, form): | |
response = super(AjaxableResponseMixin, self).form_invalid(form) | |
if self.request.is_ajax(): | |
return JsonResponse(form.errors, status=400) | |
else: | |
return response | |
def form_valid(self, form): | |
# We make sure to call the parent's form_valid() method because | |
# it might do some processing (in the case of CreateView, it will | |
# call form.save() for example). | |
response = super(AjaxableResponseMixin, self).form_valid(form) | |
if self.request.is_ajax(): | |
data = { | |
'pk': self.object.pk, | |
} | |
return JsonResponse(data) | |
else: | |
return response | |
class AuthorCreate(AjaxableResponseMixin, CreateView): | |
model = Author | |
fields = ['name'] | |
----------------------------------------------------------------------- | |
ListView with builtin pagination | |
================================ | |
{% extends "base.html" %} | |
{% block content %} | |
<h2>Publisher {{ publisher.name }}</h2> | |
<ol> | |
{% for book in page_obj %} | |
<li>{{ book.title }}</li> | |
{% endfor %} | |
</ol> | |
<div class="pagination"> | |
<span class="step-links"> | |
{% if page_obj.has_previous %} | |
<a href="?page={{ page_obj.previous_page_number }}">previous</a> | |
{% endif %} | |
<span class="current"> | |
Page {{ page_obj.number }} of {{ paginator.num_pages }}. | |
</span> | |
{% if page_obj.has_next %} | |
<a href="?page={{ page_obj.next_page_number }}">next</a> | |
{% endif %} | |
</span> | |
</div> | |
{% endblock %} | |
------------------------------------------ | |
File uploads | |
============ | |
from django.db import models | |
class Car(models.Model): | |
name = models.CharField(max_length=255) | |
price = models.DecimalField(max_digits=5, decimal_places=2) | |
photo = models.ImageField(upload_to='cars') | |
>>> car = Car.objects.get(name="57 Chevy") | |
>>> car.photo | |
<ImageFieldFile: chevy.jpg> | |
>>> car.photo.name | |
'cars/chevy.jpg' | |
>>> car.photo.path | |
'/media/cars/chevy.jpg' | |
>>> car.photo.url | |
'http://media.example.com/cars/chevy.jpg' | |
----------------------------------------------------- | |
Access value from .settings.py | |
============================== | |
from django.conf import settings | |
new_path = settings.MEDIA_ROOT | |
---------------------------------------------------- | |
Sending emails with | |
=================== | |
from django.core.mail import send_mail | |
send_mail('Subject here', 'Here is the message.', 'from@example.com', | |
['to@example.com'], fail_silently=False) | |
--------------------------------------------------------- | |
logging | |
======= | |
# import the logging library | |
import logging | |
# Get an instance of a logger | |
logger = logging.getLogger(__name__) | |
def my_view(request, arg1, arg): | |
... | |
if bad_mojo: | |
# Log an error message | |
logger.error('Something went wrong!') | |
------------------------------------------------------------ | |
Configuring static files | |
======================== | |
django.contrib.staticfiles in installed apps | |
STATIC_URL = '/static/' | |
{% load static %} | |
<img src="{% static "my_app/myexample.jpg" %}" alt="My image"/> | |
---------------------------------------------------------------- | |
Reverse lazy URL | |
================ | |
from django.views.generic.edit import DeleteView | |
from django.urls import reverse_lazy | |
from myapp.models import Author | |
class AuthorDelete(DeleteView): | |
model = Author | |
success_url = reverse_lazy('author-list') | |
------------------------------------------------------------------ | |
Adding new column with custom function in admin list | |
==================================================== | |
from django.contrib import admin | |
from myapp.models import Article | |
def make_published(modeladmin, request, queryset): | |
queryset.update(status='p') | |
make_published.short_description = "Mark selected stories as published" | |
class ArticleAdmin(admin.ModelAdmin): | |
list_display = ['title', 'status'] | |
ordering = ['title'] | |
actions = [make_published] | |
admin.site.register(Article, ArticleAdmin) | |
--------------------------------------------------- | |
Custom Message after result in custom admin list | |
=============================================== | |
class ArticleAdmin(admin.ModelAdmin): | |
... | |
def make_published(self, request, queryset): | |
rows_updated = queryset.update(status='p') | |
if rows_updated == 1: | |
message_bit = "1 story was" | |
else: | |
message_bit = "%s stories were" % rows_updated | |
self.message_user(request, "%s successfully marked as published." % message_bit) | |
---------------------------------------------------------------------------- | |
Jquery Ajax Post | |
================ | |
<script src="{% static 'student/jquery.js' %}"></script> | |
<script> | |
function getCookie(name) { | |
var cookieValue = null; | |
if (document.cookie && document.cookie != '') { | |
var cookies = document.cookie.split(';'); | |
for (var i = 0; i < cookies.length; i++) { | |
var cookie = cookies[i]; | |
// Does this cookie string begin with the name we want? | |
if (cookie.substring(0, name.length + 1) == (name + '=')) { | |
cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); | |
break; | |
} | |
} | |
} | |
return cookieValue; | |
} | |
var csrftoken = getCookie('csrftoken'); | |
</script> | |
<script type="text/javascript"> | |
$(document).ready(function() { | |
var data = { | |
'foo': 'bar' | |
} | |
$.ajaxSetup({ | |
beforeSend: function(xhr, settings) { | |
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { | |
// Only send the token to relative URLs i.e. locally. | |
xhr.setRequestHeader("X-CSRFToken", csrftoken); | |
} | |
} | |
}); | |
$.ajax({ | |
"type": "POST", | |
"dataType": "json", | |
"url": "/student/create/", | |
"data": data, | |
"beforeSend": function(xhr, settings) { | |
console.log("Before Send"); | |
$.ajaxSettings.beforeSend(xhr, settings); | |
}, | |
"success": function(result) { | |
console.log(result); | |
} | |
}) | |
}); | |
</script> | |
in views | |
........ | |
from django.shortcuts import render | |
from django.http import HttpResponse | |
from django.http import JsonResponse | |
from .models import Student | |
def create(request): | |
if(request.method=='POST'): | |
return JsonResponse(request.POST) | |
else : | |
return render(request,'student/create.html') | |
------------------------------------------------------------------- | |
Angularjs Ajax POST example | |
=========================== | |
<script> | |
function getCookie(name) { | |
var cookieValue = null; | |
if (document.cookie && document.cookie != '') { | |
var cookies = document.cookie.split(';'); | |
for (var i = 0; i < cookies.length; i++) { | |
var cookie = cookies[i]; | |
// Does this cookie string begin with the name we want? | |
if (cookie.substring(0, name.length + 1) == (name + '=')) { | |
cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); | |
break; | |
} | |
} | |
} | |
return cookieValue; | |
} | |
var csrftoken = getCookie('csrftoken'); | |
var app = angular.module('Student',[]) | |
app.config(function($httpProvider){ | |
$httpProvider.interceptors.push('httpRequestInterceptor'); | |
}) | |
app.factory('httpRequestInterceptor', | |
['$rootScope', function($rootScope) | |
{ | |
return { | |
request: function($config) { | |
$config.headers['X-CSRFToken'] = csrftoken; | |
$config.headers['Content-Type'] = 'application/x-www-form-urlencoded' | |
return $config; | |
} | |
}; | |
}]); | |
app.controller('StudentController',function($scope,$http){ | |
$scope.message = 'Hello' | |
$scope.save = function(){ | |
var data = { | |
name : "Siva via ajax" | |
} | |
$http({ | |
method: 'POST', | |
url: '/student/create/', | |
data: $.param(data) | |
}).then(function(response){ | |
console.log(response.data,'data') | |
}) | |
} | |
}) | |
</script> | |
in template | |
........... | |
{% extends "student/base.html" %} | |
{% block content %} | |
<div ng-controller="StudentController"> | |
<form action=""> | |
{% csrf_token %} | |
<input type="text" name="name"> | |
<button ng-click="save()">Save</button> | |
</form> | |
<p ng-bind="message"></p> | |
</div> | |
{% endblock %} | |
in views | |
........ | |
from django.shortcuts import render | |
from django.http import HttpResponse | |
from django.http import JsonResponse | |
from .models import Student | |
import json | |
def create(request): | |
if(request.method=='POST'): | |
s = Student(student_id=request.POST['student_id'],name=request.POST['name']) | |
s.save() | |
return JsonResponse(request.POST) | |
else : | |
return render(request,'student/create.html') | |
def list(request): | |
context = { 'lists' : Student.objects.all() } | |
return render(request,'student/list.html',context) | |
------------------------------------------------------------- | |
make links with anchor tag example | |
================================== | |
from django.conf.urls import url | |
from . import views | |
urlpatterns = [ | |
url(r'^$', views.list,name="list"), | |
url(r'^create/', views.create,name="create"), | |
] | |
in base template file | |
..................... | |
<li><a href="{% url 'create' %}">Create</a></li> | |
<li><a href="{% url 'list' %}">List</a></li> | |
--------------------------------------------------------------- | |
Pagination without using ListView | |
================================= | |
from django.shortcuts import render | |
from django.http import HttpResponse | |
from django.http import JsonResponse | |
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger | |
from .models import Student | |
import json | |
def create(request): | |
if(request.method=='POST'): | |
s = Student(student_id=request.POST['student_id'],name=request.POST['name']) | |
s.save() | |
return JsonResponse(request.POST) | |
else : | |
return render(request,'student/create.html') | |
def list(request): | |
student_list = Student.objects.all() | |
paginator = Paginator(student_list, 5) | |
page = request.GET.get('page') | |
try: | |
lists = paginator.page(page) | |
except PageNotAnInteger: | |
# If page is not an integer, deliver first page. | |
lists = paginator.page(1) | |
except EmptyPage: | |
# If page is out of range (e.g. 9999), deliver last page of results. | |
lists = paginator.page(paginator.num_pages) | |
return render(request, 'student/list.html', {'lists': lists}) | |
in views | |
........ | |
{% extends "student/base.html" %} | |
{% block content %} | |
{% for list in lists %} | |
<p>{{ list.name | lower }}</p> | |
{% endfor %} | |
<div class="pagination"> | |
<span class="step-links"> | |
{% if lists.has_previous %} | |
<a href="?page={{ lists.previous_page_number }}">previous</a> | |
{% endif %} | |
<span class="current"> | |
Page {{ lists.number }} of {{ lists.paginator.num_pages }}. | |
</span> | |
{% if lists.has_next %} | |
<a href="?page={{ lists.next_page_number }}">next</a> | |
{% endif %} | |
</span> | |
</div> | |
{% endblock %} | |
------------------------------------------------------------------ | |
Pagination and search field customization is Admin nd hide filter | |
================================================================= | |
from django.contrib import admin | |
# Register your models here. | |
from .models import Student | |
class StudentAdmin(admin.ModelAdmin): | |
fields = ['name'] | |
#list_filter = ['name'] | |
search_fields = ['name'] | |
list_per_page = 5 | |
admin.site.register(Student, StudentAdmin) | |
-------------------------------------------------------- | |
Json response for models | |
======================== | |
from django.core import serializers | |
def nglist(request): | |
return HttpResponse(serializers.serialize("json",Student.objects.all())) | |
---------------------------------------------------------- | |
angular ng-repeat example inside views | |
====================================== | |
<ul> | |
<li ng-repeat="dat in data"> | |
<span ng-bind="dat.fields.name"></span> | |
</li> | |
</ul> | |
------------------------------------------ | |
Return Errors and page not found | |
================================ | |
from django.http import HttpResponse, HttpResponseNotFound | |
def my_view(request): | |
# ... | |
if foo: | |
return HttpResponseNotFound('<h1>Page not found</h1>') | |
else: | |
return HttpResponse('<h1>Page was found</h1>') | |
--------------------------------------------------------- | |
Exception Handling Example | |
========================== | |
from django.http import Http404 | |
from django.shortcuts import render | |
from polls.models import Poll | |
def detail(request, poll_id): | |
try: | |
p = Poll.objects.get(pk=poll_id) | |
except Poll.DoesNotExist: | |
raise Http404("Poll does not exist") | |
return render(request, 'polls/detail.html', {'poll': p}) | |
----------------------------------------------- | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment