Difference between revisions of "Django"

From RHS Wiki
Jump to navigation Jump to search
m
Tag: visualeditor-switched
Tag: visualeditor
Line 1: Line 1:
= Django =
+
=Django=
==== Requirements: ====
+
====Requirements:====
* Python
 
* Database (MySQL / PostgreSQL...)
 
  
==== Installation: ====  
+
*Python
 +
*Database (MySQL / PostgreSQL...)
 +
 
 +
====Installation:====  
 
  <nowiki>pip install django</nowiki>
 
  <nowiki>pip install django</nowiki>
  
==== Create project ====
+
====Create project====
 
  <nowiki>django-admin.py startproject mysite</nowiki>
 
  <nowiki>django-admin.py startproject mysite</nowiki>
  
==== Database Setup ====
+
====Database Setup====
 
Edit: mysite/settings.py
 
Edit: mysite/settings.py
  
 
In DATABASES = {...
 
In DATABASES = {...
* ENGINE – Either 'django.db.backends.sqlite3', 'django.db.backends.postgresql_psycopg2', 'django.db.backends.mysql', or 'django.db.backends.oracle'.
+
 
 +
*ENGINE – Either 'django.db.backends.sqlite3', 'django.db.backends.postgresql_psycopg2', 'django.db.backends.mysql', or 'django.db.backends.oracle'.
 
*NAME – The name of your database.
 
*NAME – The name of your database.
 
*USER – Username for the database.
 
*USER – Username for the database.
Line 25: Line 27:
 
(pip install MySQL-python)
 
(pip install MySQL-python)
  
==== Run App in development server ====
+
====Run App in development server====
 
If the server is an amazon aws:
 
If the server is an amazon aws:
 
  <nowiki>python manage.py runserver 0.0.0.0:8000 </nowiki>
 
  <nowiki>python manage.py runserver 0.0.0.0:8000 </nowiki>
Line 37: Line 39:
 
then kill process
 
then kill process
  
==== Create an app ====
+
====Create an app====
 
  <nowiki>python manage.py startapp appname</nowiki>
 
  <nowiki>python manage.py startapp appname</nowiki>
  
==== Create admin user ====
+
====Create admin user====
 
python manage.py createsuperuser
 
python manage.py createsuperuser
 
access at http://serverurl:8000/admin
 
access at http://serverurl:8000/admin
  
==== Usefull packages ====
+
====Usefull packages====
===== Django Allouth =====
+
=====Django Allouth=====
 
[http://django-allauth.readthedocs.org/en/latest/showcase.html User Registration]<br />
 
[http://django-allauth.readthedocs.org/en/latest/showcase.html User Registration]<br />
 
[http://www.sarahhagstrom.com/2013/09/the-missing-django-allauth-tutorial/ Allouth Tutorial]
 
[http://www.sarahhagstrom.com/2013/09/the-missing-django-allauth-tutorial/ Allouth Tutorial]
===== Django registration =====
+
=====Django registration=====
 
Not working in Django 1.7<br>
 
Not working in Django 1.7<br>
 
[http://django-registration.readthedocs.org/en/latest/quickstart.html User registration]<br>
 
[http://django-registration.readthedocs.org/en/latest/quickstart.html User registration]<br>
 
[https://devdoodles.wordpress.com/2009/02/16/user-authentication-with-django-registration/ Django registration step by step]
 
[https://devdoodles.wordpress.com/2009/02/16/user-authentication-with-django-registration/ Django registration step by step]
= CBV =
+
=CBV=
== CSRF Exempt ==
+
==CSRF Exempt==
<source lang="python">class ChromeLoginView(View):
+
<source lang="python">class ChromeLoginView(View):
 
     @method_decorator(csrf_exempt)
 
     @method_decorator(csrf_exempt)
 
     def dispatch(self, request, *args, **kwargs):
 
     def dispatch(self, request, *args, **kwargs):
Line 71: Line 73:
 
                 return JsonResponse({'status': True})
 
                 return JsonResponse({'status': True})
 
         return JsonResponse({'status': False})</source>
 
         return JsonResponse({'status': False})</source>
= Notes =
+
=Notes=
== Templates ==
+
==Templates==
 
  href="{% static 'cpc/css/tree.css' %}"
 
  href="{% static 'cpc/css/tree.css' %}"
 
  href="{% url 'civilarea_history_create' task.id %}"
 
  href="{% url 'civilarea_history_create' task.id %}"
=== Change language template ===
+
===Change language template===
  <source lang=django><form action="{% url 'set_language' %}" method="post">
+
  <source lang="html+django"><form action="{% url 'set_language' %}" method="post">
{% csrf_token %}
+
    {% csrf_token %}
<input name="next" type="hidden" value="{{ redirect_to }}" />
+
    <input name="next" type="hidden" value="{{ redirect_to }}" />
<select name="language">
+
    <select name="language">
{% get_language_info_list for LANGUAGES as languages %}
+
        {% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
+
        {% for language in languages %}
<option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}>
+
            <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}>
    {{ language.name_local }} ({{ language.code }})
+
                {{ language.name_local }} ({{ language.code }})
</option>
+
            </option>
{% endfor %}
+
        {% endfor %}
</select>
+
    </select>
<input type="submit" value="Go" />
+
    <input type="submit" value="Go" />
 
</form></source>
 
</form></source>
  
== Reset Migrations ==
+
==Reset Migrations==
  
 
1) Fake migrations back to 0
 
1) Fake migrations back to 0
Line 104: Line 106:
 
  ./manage.py migrate app --fake
 
  ./manage.py migrate app --fake
  
== Check for connected signals listeners ==
+
==Check for connected signals listeners==
 
   from django.db.models.signals import *
 
   from django.db.models.signals import *
 
   for signal in [pre_save, pre_init, pre_delete, post_save, post_delete, post_init]:
 
   for signal in [pre_save, pre_init, pre_delete, post_save, post_delete, post_init]:
 
       # print a List of connected listeners
 
       # print a List of connected listeners
 
       print(signal.receivers)
 
       print(signal.receivers)
== Use Django ORM from python script ==
+
==Use Django ORM from python script==
 
  <nowiki>import os
 
  <nowiki>import os
import django
+
import django
os.environ["DJANGO_SETTINGS_MODULE"] = 'project.settings'
+
os.environ["DJANGO_SETTINGS_MODULE"] = 'project.settings'
django.setup()
+
django.setup()
from .models import</nowiki>
+
from .models import</nowiki>
 
or
 
or
 
  python manage.py shell < script.py
 
  python manage.py shell < script.py

Revision as of 07:52, 27 March 2019

Django

Requirements:

  • Python
  • Database (MySQL / PostgreSQL...)

Installation:

pip install django

Create project

django-admin.py startproject mysite

Database Setup

Edit: mysite/settings.py

In DATABASES = {...

  • ENGINE – Either 'django.db.backends.sqlite3', 'django.db.backends.postgresql_psycopg2', 'django.db.backends.mysql', or 'django.db.backends.oracle'.
  • NAME – The name of your database.
  • USER – Username for the database.
  • PASSWORD – Password for the database.
  • HOST – Database HOST.

To create the database tables execute from the project folder:

python manage.py migrate

(pip install MySQL-python)

Run App in development server

If the server is an amazon aws:

python manage.py runserver 0.0.0.0:8000 

Else:

python manage.py runserver

To run server as daemon:

nohup python manage.py runserver 0.0.0.0:8000

To stop the daemon:

ps -ef | egrep python manage.py

then kill process

Create an app

python manage.py startapp appname

Create admin user

python manage.py createsuperuser access at http://serverurl:8000/admin

Usefull packages

Django Allouth

User Registration
Allouth Tutorial

Django registration

Not working in Django 1.7
User registration
Django registration step by step

CBV

CSRF Exempt

class ChromeLoginView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super(ChromeLoginView, self).dispatch(request, *args, **kwargs)

    def get(self, request):
        return JsonResponse({'status': request.user.is_authenticated()})

    def post(self, request):
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return JsonResponse({'status': True})
        return JsonResponse({'status': False})

Notes

Templates

href="{% static 'cpc/css/tree.css' %}"
href="{% url 'civilarea_history_create' task.id %}"

Change language template

<form action="{% url 'set_language' %}" method="post">
    {% csrf_token %}
    <input name="next" type="hidden" value="{{ redirect_to }}" />
    <select name="language">
        {% get_language_info_list for LANGUAGES as languages %}
        {% for language in languages %}
            <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}>
                {{ language.name_local }} ({{ language.code }})
            </option>
        {% endfor %}
    </select>
    <input type="submit" value="Go" />
</form>

Reset Migrations

1) Fake migrations back to 0

./manage.py migrate app zero --fake

2) Delete migrations files

rm "app/migrations/*"

3) Create new migration file

./manage.py makemigrations app

4) Pretend to run the new migration

./manage.py migrate app --fake

Check for connected signals listeners

 from django.db.models.signals import *
 for signal in [pre_save, pre_init, pre_delete, post_save, post_delete, post_init]:
     # print a List of connected listeners
     print(signal.receivers)

Use Django ORM from python script

import os
 import django
 os.environ["DJANGO_SETTINGS_MODULE"] = 'project.settings'
 django.setup()
 from .models import

or

python manage.py shell < script.py