This is sort of a cheating sheet for a simple django application. You can get ideas on how to create a fully functional django application.
- Create a project and a application
to start a project, go to directory you want to creat the application, do the following:
django-admin startproject <your_project_name>
then cd to that project folder,
django_admin startapp <your_app_name>
- Create template folder
Because django is a MTV (model-template-views) framework –although I think it is sort of like MVC framework and Views in MTV is just like the Controller in MVC and Template is just like the Views in MVC – so that it is better to have a seperate folder to cache all the templates and makes the app clean. following is the tree view of the whole project.
your_project
|
--your_app1
|
--your_app2
|
...
|
--templates
|
--your_app1
| |
--your_app1.html
| |
...
|
--your_app2
once you have templates folder, you want to register template folder in settings.py.
by giving TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates'), you will get templates directory. One more step, find variable TEMPLATES, and in this list, you can find DIRS. Then add TEMPLATE_DIR in DIRS list.
- register app in
settings.py
find INSTALLED_APPS, and then add <your_appx>’s name in INSTALLED_APPS list.
- create models
TBD
create forms
- To create forms is very similar with to create a model. Instead of
models.pyis generic, you have to manually create aforms.py. You then want to import and create form stuff.
here is a simple
forms.pyfilefrom django import forms def FormName(forms.Form): name = forms.CharField() email = forms.CharField() text = forms.CharField(widget = forms.Textarea)and then after you create a
forms.py, you need to show it by using aviews.pyAs always, in
views.py, we need to import forms. there are two ways of doing itfrom . imports formsfrom forms import Formname(I don’t quite understand this methord)
after importing, we use
render()to give the form to template just like before. something like following:def form_name_view(request): form = forms.FormName() return render(request, 'form_name.html', {'form':form})take care of
urls.pymodify html files
inject forms by using
{{ form }}is the most basic way of doing it.more complete snippet see the following:
<div class = "container"> <form method = "POST"> {{ form.as_p }} {% csrf_token %} <input type = "submit" class = "btn btn-primary" value = "Submit"> </form> </div>calling
{{ form.as_p }}will create form from top to bottom instead of from left to right. In other words, the layout is prettier.because of django security measures, you have to add
{% csrf_token %}, or it would fail.- receive form
post
we can access a dictionary like attribute of the
cleaned_data[]something like the following:
... print('<your_key_name>: '+ form.cleaned_data['<your_key_name>']) ...- To create forms is very similar with to create a model. Instead of
form validation
- dummy validation
in
forms.py, hidden field can be used for validation.we use hidden fields. just add a new field in the model in
forms.py.after we add a hidden field, maybe call it ‘botcatcher’, assign that
widget = forms.HiddenInput. If a bot came in, it will change the input’s value, but since human won’t see it, we can catch this bot. informs.py, we can have another method calledclean_<your_hidden_fields_name>, use built-in functionself.clean_data['botcatcher'], we can get the value of input. if value length is greater than 0, thenraise ValidationError. raise error will print message on page.- generic validation
from django.core import validatorthen pass in
validatorparameter to do validation.- customize validation function
just create a new function, and then pass it into
validator = [<your_function>]- use clean data
if you wants to use clean data, just use
super().clean()form model
form model can easily ’exploit’ your models that is already there and make them into form.
class Meta():
see django documentation
- about
views.py, my understanding
views here in django is just like controller in traditional MVC framework. it is not really a actually view or I should say html file or template, but it is a ‘controller’ to control what to show in django template.
- templates tagging and inheritance
firstly in apps urls.py, we need to set a namespace. app_name = <your_app_name>
see documentation
{% block body_block %} {% endblock %}
{% extend <your_base_html_file> %}
- django filter
say you want to display all capital letters in one page and display all lower letters in another page, that is why we use filters.
see documentation django templates
{{ value| filter: "parameter" }}
{% load my_templates %}
- user authentication
in settings.py file:
two useful packeage:
pip install bcrypt
pip install django[argon2]
then you probably want to do password validation, that comes to PASSWORD_HASHERS, this must be added manually.
after that, you take care of directories. like template dir, static dir and media dir. Don’t forget to add folders named templates, static and media.
now the modification in settings.py is done.
then to create user authorization models.
in models.py file: as introductions saying
in forms.py file: as introduction saying
in admin.py file: as introduction saying
we have to prepare this 3 files first.
then create the templates
at last, just modify views.py, urls.py
- deployment choices
mkvirtualevn --python=python3.6 myproj
the above is to create a virtual enviroment for pythonanywhere
pip list
check tools
- Class based views(CBV)
from django.views.generic import View
in views.py, views would be written as a Class, maybe called Class CBView(View)
and then, in urls.py, could call url(r'^$', views.CBView.as_view())
CBV to call template view, you do this:
from django.views.generic import TemplateView
class IndexView(TemplateView):
template_name = 'index.html'
for injecting dictionary to html, it is like the following:
class IndexView(TemplateView):
template_name = 'index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['<your_inject_key>'] = '<your_value>'
return context
- detail view and list view
from django.views.generic import ListView, DetailView
from django.views.generic import ListView, DetailView
class SchoolListView(ListView):
model = models.School
class SchoolDetailView(DetailView):
model = models.School
template_name = 'basic_app/school_detail.html'