Oliva Apps Ltd
Ajax requests with jQuery/Django
# urls.py
path("api/values/", values_view, name="values api")
path("api/values/<int:value_id>/", value_view, name="value api")

# template
$.ajax({
    url: "{% url 'values api' %}",
    method : 'POST',
    data: { 'new_value': value, },
    dataType: 'json',  // expecting JSON response back
    headers : { "X-CSRFToken" : $("[name=csrfmiddlewaretoken]").val() },
    success: function (data, textStatus, jqXHR) {
       console.log(data)
    },
    error: function (jqXHR, textStatus, errorThrown) {
       console.log(errorThrown)
    }
})
$.ajax({
    url: "{% url 'value api' value_id %}",
    method : 'DELETE',
    dataType: 'json',  // expecting JSON response back
    headers : { "X-CSRFToken" : $("[name=csrfmiddlewaretoken]").val() },
    success: function (data, textStatus, jqXHR) {
       console.log(data)
    },
    error: function (jqXHR, textStatus, errorThrown) {
       console.log(errorThrown)
    }
})
$.ajax({
    url: "{% url 'value api' value_id %}",
    method : 'PUT',
    data: { 'new_value': value, },
    dataType: 'json',  // expecting JSON response back
    headers : { "X-CSRFToken" : $("[name=csrfmiddlewaretoken]").val() },
    success: function (data, textStatus, jqXHR) {
       console.log(data)
    },
    error: function (jqXHR, textStatus, errorThrown) {
       console.log(errorThrown)
    }
})

# views.py
def values_view(request):
    if request.method == 'POST':
        value = POST['new_value']
        # save new value...
        return JsonResponse({ 'result': 'success' })

def value_view(request, value_id):
    if request.method == 'DELETE':
        value = Value.objects.get(id=value_id)
        # delete value...
        return JsonResponse({ 'result': 'success' })
    if request.method == 'UPDATE':
        UPDATE = QueryDict(request.body)
        value = Value.objects.get(id=value_id)
        new_value = UPDATE['new_value']
        # update value...
        return JsonResponse({ 'result': 'success' })


CSS
YouTube: 10 modern layouts in 1 line of CSS
Code: https://1linelayouts.glitch.me/

Basic conda commands
$ conda create --name <env_name> python=3
$ conda info --envs
$ source activate <env_name>
$ source deactivate <env_name>
$ conda env remove --name <env_name>



Postgres basic commands
# Start postgres prompt
$ sudo -u postgres psql

# Create a database
postgres=# CREATE DATABASE <myproject>;

# Create a user
postgres=# CREATE USER <myprojectuser> WITH PASSWORD <'password'>;

# Django's recommended settings
postgres=# ALTER ROLE myprojectuser SET client_encoding TO 'utf8';
postgres=# ALTER ROLE myprojectuser SET default_transaction_isolation TO 'read committed';
postgres=# ALTER ROLE myprojectuser SET timezone TO 'UTC';

django-rest-framework: A powerful and flexible toolkit for building Web APIs
$ pip install djangorestframework
$ pip install markdown       # Markdown support for the browsable API.
$ pip install django-filter  # Filtering support
django-crispy-forms: Rendering of Django forms in a very elegant and DRY way
$ pip install django-crispy-forms

# forms.py
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Row, Column, Layout, Submit, Hidden, Button, Field, Div, HTML
from crispy_forms.bootstrap import FormActions

class MyForm(forms.Form):
    '''My Sample Form'''
    email_field = forms.EmailField(label='Email')
    password_field = forms.CharField(
        label='Password',
        max_length=50,
        widget=forms.PasswordInput,
    )
    date_field = forms.DateField(
        widget=forms.DateInput(
            format='%d/%m/%Y',
            attrs={'autocomplete':'off'},
        ),
        input_formats=('%d/%m/%Y',)
    )
    select_field = forms.ModelChoiceField(
        label='Choice',
        queryset=None,
        required=False,
    )

    helper = FormHelper()
    helper.form_id = 'my-form'
    helper.form_method = 'POST'
    helper.layout = Layout(
        Row(
            Column('email_field', css_class='col-6 mb-0'),
            Column('password_field', css_class='col-6 mb-0'),
            css_class='form-row mb-0'
        ),
        Field('date_field'),
        Field('select_field'),
        FormActions(
           Div(
               Button('login', 'Log in', css_class='btn-primary'),
               css_class='d-inline float-left',
           ),
           Div(
              HTML("<a class='mt-4' href='/reset_password/'>Forgot password?</a>"),
              css_class='d-inline float-right mt-2',
           ),
           css_class='mt-4',
       )
    )

    def __init__(self, *args, **kwargs):
        # can pass extra arguments to the form constructor
        user = kwargs.pop('user', None)
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['select_field'].queryset = user.choices.all()

Git
BGF repo-cleaner: Removing sensitive data or large files from your git history
# 1. clone a fresh copy of your repo, using the --mirror flag:
$ git clone --mirror <git://example.com/my-repo.git>

# 2. run the BFG to clean your repository up (e.g. remove large files)
$ bfg --strip-blobs-bigger-than 50M  my-repo.git

# 3. use the standard git gc command to strip out the unwanted dirty data
$ cd <my-repo.git>
$ git reflog expire --expire=now --all && git gc --prune=now --aggressive

# 4. push it back up
$ git push

# 5 ditch old copies of the repo and do fresh clones of the nice, new pristine data
$ git clone <git://example.com/my-repo.git>

Serialising a form with jQuery
var my_form_data = $("#myform").serialize()

Obtain (or renew) SSL certificates with certbot on Nginx
$ sudo certbot --nginx -d example.com -d www.example.com
$ sudo certbot renew --dry-run

Chart.js
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
            ],
            borderWidth: 1
        }]
    },
});
</script>
Google code-prettify: An embeddable script that makes source-code snippets in HTML prettier.
<script src="https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js"></script>
<code class="prettyprint">
   # Code written here will be prettified
</code>

SSH
Using SSH agent
$ eval "$(ssh-agent -s)"      # start ssh agent in the background
$ ssh-add -l                  # list all keys in agent
$ ssh-add -D                  # clean up all keys
$ ssh-add -k ~/.ssh/id_rsa    # add a key
Avoid typing SSH password with ForwardAgent (in .ssh/config)
Host <name>
  HostName <ip_address>
  User <username>
  ForwardAgent yes

nginx useful commands
# test nginx configuration
$ sudo nginx -t

# restart nginx
$ sudo systemctl restart nginx




DateTimePicker: Flexible jQuery plugin for picking date and time
<input id="datetimepicker" type="text">
<script>
   $('#datetimepicker').datetimepicker({
      startDate:'+1971/05/01',    //or 1986/12/08
      allowTimes:[
         '12:00', '13:00', '15:00', 
         '17:00', '17:05', '17:20', '19:00', '20:00'
      ]
   })
</script>
jQuery UI Sortable: Rearrange a list using drag and drop
$(function() {
  $("#sortable").sortable()
})