The goal of efficiency is more slack.

Showing posts with label Django. Show all posts
Showing posts with label Django. Show all posts

Tuesday, September 17, 2019

Sites for Django

How to use the Sites package for Django.

Follow instructions in documentation to install the Sites package. Then create a migration in one of your apps.

from __future__ import unicode_literals

from django.db import migrations

def set_site_name(apps, schema_editor):
    Site = apps.get_model('sites', 'site')
    try:
        site = Site.objects.get(id=1)
    except Site.DoesNotExist:
        site = Site()
    site.name = "Astrobiology"
    site.domain = "astrobiology.nasa.gov"
    site.save()

class Migration(migrations.Migration):

    dependencies = [
        ('sites', '0002_alter_domain_unique'),
    ]

    operations = [
        migrations.RunPython(set_site_name),
    ]


Enter the latest migration from the "sites" app as a dependency to ensure there is a database table for sites.

On the development computer, run ./manage shell and change the domain of the site object to 127.0.0.1:8000.

Sunday, June 16, 2019

FeinCMS installation

Following directions at https://feincms-django-cms.readthedocs.io/en/stable/installation.html, I ran into some problems, probably due to a Django version mismatch. I'm using Django 1.11.x. This second tutorial helped fill in some blanks: https://www.digitalocean.com/community/tutorials/how-to-install-and-get-started-with-feincms . Below are my additions to the first documentation link.

Don't add context processors to the default set Django startproject created.

Create a folder for templates. Add it to settings.py:
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'my_project/templates'),
        ],

Create a template base.html with at least the following:
{% block content %} {% for content in feincms_page.content.main %} {{ content.render }} {% endfor %} {% endblock %}

Create a new Django project in VSCode

  • Go to user settings (cmd-,):
"python.venvPath": "~/.virtualenvs",
  • Quit VSCode.
  • Open a Python file in VSCode.
  • Select virtualenv in bottom bar.
  • Debug > Open Configurations to create launch.json. Otherwise, "Add Configurations" may not work.
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Server",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/manage.py",
            "args": [
                "runserver",
                "--noreload",
            ],
            "debugOptions": [
                "RedirectOutput",
                "Django"
            ]
        },
        {
            "name": "Script",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/manage.py",
            "args": [
                "runscript",
                "$(basename -s .py ${file})"
            ],
            "debugOptions": [
                "RedirectOutput",
                "Django"
            ]
        }
    ]
}
  • Click button on bottom right to Install Linting.

Install Django on a development Mac

Notes on installing a Django development environment on a Mac.

Install Python

  • Install Python 3 from www.python.org.
  • Run Install Cerltificates.command.
  • Install pip and virtualenv
pip3 install --upgrade pip
pip3 install virtualenvwrapper
Put virtualenvwrapper in .bash_profile:
# Virtualenvwrapper
export VIRTUALENVWRAPPER_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
source /Library/Frameworks/Python.framework/Versions/3.6/bin/virtualenvwrapper_lazy.sh

Create a Python virtual environment

mkvirtualenv -p /usr/bin/python2 my_proj
cd ~/Documents/my_proj
setvirtualenvproject
-p is optional

Install Visual Studio Code

  • Install shell command: Cmd-Shift-p > shell command
  • Install Python extension.

Install Postgres


Install Django

pip install Django

Create directory

cd to the parent directory of the directory you wish to place the source files.
Create directory for source files with the Django startapp command.
django-admin startproject my_proj
cd my_proj
setvirtualenvproject

Create app

mkdir my_proj/my_form
./manage.py startapp my_form my_proj/my_form

Configure for VSCode

code . 
Create a new Django project in VSCode

Initialize git

git init
git add .
If .pyc files were uninentionally added:
git rm --cached '**.pyc'

Create .gitignore

touch .gitignore
code .gitignore
Input:
*.pyc

Static files

STATIC_URL: URL (relative to domain root) to trigger searching for static files.
STATICFILES_DIRS: List of directories in which to look for static files when collectstatic is run.
STATIC_ROOT: Django serves files from this directory when run under development mode. Also, collectstatic collects static files here. Upload this to server.

In development: project/static, sibling to project/manage.py
On production: /home/user/domain.com/public/static

settings.py:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'public/static/')   

Friday, March 22, 2019

Django in a subdirectory

How to serve a Django project as a subdirectory of another Django project's URL. For example, the first Django site is at www.example.com/ and the second site is at www.example.com/second-site/.

Software Used

  • Nginx
  • Uwsgi 2
  • Django

Procedure

yum install uwsgi-router-rewrite

Add route-uri to uwsgi configuration /etc/uwsgi.d/example.ini
 [uwsgi]

# Python
plugin = python36, router_rewrite

# Django
chdir = /srv/sites/example
module = example.wsgi
home = /srv/.virtualenvs/example
route-uri = ^/second-site(.*) rewrite:$1

# Process
master = true
processes = 5
socket = /run/uwsgi/example.sock
vacuum = true
procname-prefix-spaced = example
Nginx configuration
server {
...
    location /
second-site/static {
        access_log off;
        alias /
var/www/second-site/static;
    }

    location /second-site/ {
        include uwsgi_params;
        uwsgi_pass unix:/run/uwsgi/example.sock;
    }
Configure Django to prefix the subdirectory name to redirects. In settings.py:
FORCE_SCRIPT_NAME = '/second-site'

STATIC_URL = FORCE_SCRIPT_NAME + '/static/'
STATIC_ROOT = '/var/www/
second-site/static'

MEDIA_URL = FORCE_SCRIPT_NAME + '/media/'
ADMIN_MEDIA_PREFIX = FORCE_SCRIPT_NAME + '/admin_media/'
SESSION_COOKIE_PATH = FORCE_SCRIPT_NAME
Reference: https://stackoverflow.com/questions/44987110/django-in-subdirectory-admin-site-is-not-working
(TODO)

Monday, September 25, 2017

Logging in Django

To log to console in Django. Source: Logging | djangoproject.com

settings.py 

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
        },
    },
}

File that uses logging

import logging
logger = logging.getLogger('django')

Write to log

logger.info('Hello')

Friday, September 08, 2017

Django Forms

Some common uses of Django Forms.

f = Form(request.POST)
Instantiating a form with data a dictionary, e.g. from POST, creates a form populated with the field-name & field-value pairs in the dictionary.

f.errors
Returns dictionary of errors with keys being field names.

f['field_name'].errors
Returns list of errors for the specified field.

bound_form = self.form_class(request.POST)
return render(request, self.template_name, {'form': bound_form})
In a class-based view, renders a form with data bound from POST. bound_form.is_bound returns True.

model_instance = get_object_or_404(
            self.form_class.Meta.model, slug__iexact=slug)

bound_form = self.form_class(request.POST, instance=model_instance)
As with previous line, renders a form with data bound from POST but also associated with a model instance so that it can be modified with a subsequent:
model_instance = bound_form.save()

form_class(initial={'title': 'Something'})
Creates a form with a field filled in already. However, the form is not bound.

Popular Posts

Recent Posts

Unordered List

Text Widget

Pages

Powered by Blogger.
Scroll To Top