Django framework webpage creation issues.
1. After SSH conection with hosting has been established install a virtual enviroment. Your python version should be same as on server (3.8.8 in my example). // Check available versions $ ls -la /opt/python/*/bin/python
2. Create a python virtual enviroment -bash-4.2$ /opt/python/python-3.8.8/bin/python -m venv djangoenv
3. Activate virtual enviroment
4. Install django and client for MySQL // $ pip install --upgrade pip
$ pip install django && CFLAGS="-std=c99"
$ pip install mysqlclient
5. Go to website catalog and clear files
6. Create django project $ django-admin startproject mydiary
6.1 To make app use $ django-admin startapp myapp // Create folder
7. Setup settings.py file $ vim settings.py // ALLOWED_HOSTS=[‘sitename’,’www.sitename’]
8. Set database in settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'u0000000',
'USER': 'u0000_pppp',
'PASSWORD': '11111',
'HOST': 'localhost',
}
}
9. Add STATIC_ROOT='static/'
10. Create static catalog $ python mydiary/manage.py collectstatic // Created directory with static files
11. Fullfill database with tables $ python manage.py migrate
12. Create file start page passenger_wsgi.py in root directory and fill it:
# -*- coding: utf-8 -*-
import os, sys
sys.path.insert(0, '/var/www/u0000/data/www/my.site/mydiary')
sys.path.insert(1, '/var/www/u0000/data/djangoenv/lib/python3.8/site-packages')
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproj.settings'
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
13. Now web page should appear in browser
14. To change project create .restart-app in root directory.
15. Install backend // $ python manage.py createsuperuser and you get backend on admin/login
16. I’ve tried to create ‘published’ column for article model but get an error while tried to migrate the new field into the database. It is detected old column which is now deleted.
// I’ve restarted eclipse IDE. Doesn’t help.
// I’ve restarted mysql $ sudo systemctl restart mysql doesn’t helped. And now I get unapplied migration message when I start webserver.
// I’ve deleted last items from database migration table. But they appeared again after migration command.
// I’ve deleted migrations folder from app directory. It helped.
17. To choose precise <model-object-name>.objects.filter(<model-parameter>=<number-of-category-id>)
19. Install package $ pip install django-tinymce4-lite
20. In settings.py type:
INSTALLED_APPS = (
'tinymce',
)
20.1. Got an import error. Cannot import name ‘smart_text’ from ‘django.utils.encoding’.
// Try to add in django/lib/python3.8/site-packages/tinymce/widgets.py:
try:
from django.utils.encoding import smart_text
except ImportError:
from django.utils.encoding import smart_str as smart_text
// It helped.
21. In settings.py add:
TINYMCE_DEFAULT_CONFIG = {
'height': 360,
'width': ‘100%’,
'cleanup_on_startup': True,
'custom_undo_redo_levels': 20,
'selector': 'textarea',
'theme': 'modern',
'plugins': '''
textcolor save link image media preview codesample contextmenu
table code lists fullscreen insertdatetime nonbreaking
contextmenu directionality searchreplace wordcount visualblocks
visualchars code fullscreen autolink lists charmap print hr
anchor pagebreak
''',
'toolbar1': '''
fullscreen preview bold italic underline | fontselect,
fontsizeselect | forecolor backcolor | alignleft alignright |
aligncenter alignjustify | indent outdent | bullist numlist table |
| link image media | codesample |
''',
'toolbar2': '''
visualblocks visualchars |
charmap hr pagebreak nonbreaking anchor | code |
''',
'contextmenu': 'formats | link image',
'menubar': True,
'statusbar': True,
'font_formats': "Titillium Web=Titillium Web,times;" +
"Andale Mono=andale mono,times;" +
"Arial=arial,helvetica,sans-serif;" +
"Arial Black=arial black,avant garde;" +
"Book Antiqua=book antiqua,palatino;" +
"Comic Sans MS=comic sans ms,sans-serif;" +
"Courier New=courier new,courier;" +
"Georgia=georgia,palatino;" +
"Helvetica=helvetica;" +
"Impact=impact,chicago;" +
"Symbol=symbol;" +
"Tahoma=tahoma,arial,helvetica,sans-serif;" +
"Terminal=terminal,monaco;" +
"Times New Roman=times new roman,times;" +
"Trebuchet MS=trebuchet ms,geneva;" +
"Verdana=verdana,geneva;" +
"Webdings=webdings;" +
"Wingdings=wingdings,zapf dingbats",
'fontsize_formats': "8pt 10pt 11pt 12pt 13pt 14pt 16pt 18pt 20pt 24pt 36pt",
}
22. Add path to min url path('tinymce/', include('tinymce.urls'))
// I’ve got error: ImportError: cannot import name 'url' from 'django.conf.urls'
22.1 Try to replace path('tinymce/', include('tinymce.urls')) with re_path('tinymce/', include('tinymce.urls')) // Doesn’t helped.
22.2. In file django/lib/python3.8/site-packages/tinymce/urls.py substitute url with path. And substitute from django.conf.urls import url with from django.urls import path at the head // Helped.
23. In admin.py add:
from tinymce.widgets import TinyMCE
from django.db import models
formfield_overrides = {
models.TextField: {'widget': TinyMCE()},
}
24. To insert html tags in django template use <variable>|safe
25. While run $ django-admin makemessages --all –ignore=env got an error: Can't find xgettext. Make sure you have GNU gettext tools 0.15 or newer installed.
//Try $ sudo apt-get install -y gettext // It fixed the issue
25.1 In the settings.py file add:
LANGUAGES = (
('en', _('English')),
('es', _('Spanish')),
)
26. To made language tags as part of url like in Joomla into urls.py file add from django.conf.urls.i18n import i18n_patterns then modify urlpattern array into urlpatterns = i18n_patterns()
27. In settings MIDDLEWARE array add localmiddleware module between session and common modules:
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware', # localization staf put here between session... and common...
'django.middleware.common.CommonMiddleware',
]
28. Install django parler module. It creates separate tables in database for separate languages. $ pip install django-parler and add ‘parler’ in settings Insatlled_apps array.
29. In settings PARLER_DEFAULT_LANGUAGE_CODE = 'en' and
PARLER_LANGUAGES = {
None: (
{'code': 'en',}, # English
{'code': 'fr',}, # French
{'code': 'es',}, # Spanish
),
'default': {
'fallbacks': ['en'],
'hide_untranslated': False,
}
}
30. In model.py file use classes as below:
from parler.models import TranslatableModel, TranslatedFields
class Someclass(TranslatableModel):
translations = TranslatedFields(
)
31. In admin.py type:
from parler.admin import TranslatableAdmin
admin.site.register(Someclass, TranslatableAdmin)
32. From time to time I get problems with migrations. The problem because of mySQL database. // Forget to put commas.
32.1 Try to delete all the Foreign keys and migrate.
33. If I have a problem with debugging in Eclipse “Port is busy” just restart eclipse IDE.
34. To create submenus use:
{% regroup some by title as name %}
{% for x in name %}
<li class="nav-item dropdown">
<a class="btn btn-outline-success" href="#">{{x.grouper}}</a>
<ul class="navbar-nav bg-dark dropdown-container">
{% for y in x.list %}
<li><a class="btn btn-outline-success" href="#">{{y.titl}}</a></li>
{% endfor %}
</ul>
</li>
{% endfor %}
34.1 I have to make language switcher to provide same article translated on switch event. For this I’ll use request.path to get current url.
35. I've created new app. Added path to urlpatterns = i18n_patterns() but I get "doesn't correspond to anything we know off"
35.1. Do migrations // Doesn't helped
35.2 Add TranslatedModel class in models.py
35.3 I deleted slash from path's end from url.py and change void path "" for something then added slash to app's url.py // Strated to work
36. When in admin panel I change language I get an error "TypeError __str__ returned non-string" // Use __unicode__(self):
36.1. Run migrations. // Nothing
36.2. In model delete def __str__(self): function // helped
37. On the main page I have full list of articles but I need only articles for specific language but even if the article doesn't have translation it appears in english. // Check 39.1
37.1. Maybe in settings.py set hide_untranslated: True // No
38. Common problem with Django is broken migratiion. When I fix db problems manually I still have errors in Django because of stupid design of django framework. // When I have problems with migrations use migrate --fake-initial or migrate --run-syncdb or --empty
39. I forget how in view.py access parler class parameters from model.py.
39.1. Try to:
from parler.utils import get_active_language_choices
Article2.objects.filter(
translations__language_code__in=get_active_language_choices(),
translations__slug='omelette'
)
It works. It is solution for 37 problem.
40. How to switch off fallback language. If I don't have translation for some language and I switch to this language I got english version but with url coresponding to other language.
40.1. In settings.py set 'fallbacks' :None // Its break website
40.2. Set fallbacks to some rare unexisting language code. // It is better but I would like don't have notavalable languages in language switcher at all.
40.3. Probably I have to try django-hvad instead of Parler
41. Problem with chinese language in django-parler. Watch file global_settings.py from django/conf package folder. Instead of "simplified chinese" use "Chinese Simlified" or vise versa.
42. How to use translated alias.
1. Install $ pip install django-hvad
35. Install pillow package. $ pip install pillow
36. I need to get information how to reset migrations list because I missed to sync some changes and database is out of sync. I just manually delete all rows from firs migrations file. // Not an option.
36.1 $ manage.py migrate --fake <appname> zero → recreate folder with migrations → $ python manage.py makemigrations → $ python manage.py migrate --fake // That works
37. $ git init in working directory
38. Django add favicon. Add to base template into head : <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/>
50. To make url unique in model field add unique=True
51. I run manage.py and got SyntaxError: invalid syntax on line 21 // I forget to start virtual enviroment.
52. While I run the migrate command I’ve got OperationalError Unknown column 'django_content_type.name' in 'field list'
52.1 I’ve deleted the table django_content_type from SQL database // It was bad idea. Now I get ProgrammingError: "Table 'django1.django_content_type' doesn't exist.
53. Use from django.core.paginator import Paginator class:
articles = Article.objects.order_by('id')
paginator = Paginator(articles, 20)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
context= { 'items':page_obj, }
54. In template:
<ul>
<li> Cur page: <b> {{items.number}} </b> </li>
{% for p in items.paginator.page_range %}
<li><a href="{% url 'site:site' %}?page={{p}}" class="{% if p == items.number %} current {% endif %}"> {{ p }} </a></li>
{% endfor %}
</ul>
54. Try to use in template: {{ value|truncatewords:20 }}
55. Can't reach admin panel. Got redirect to admin/login/ and got an error DoesNotExist at /admin/login/
55.1. Set SITE_ID=1 in settings.py // helped but I loose translations ((
55.2. So. I've logged in while SITE_ID=1 then cleared the settings. And I am able to use admin panel while session is active on current browser.
56. Got server 500 error while trying to add translation for a category. // maybe url.py add admin to i18n_pattern // no
56.1. Check settings.py // but its identical.
56.2. Enable DEBUG. // Helped. It is about __str__ thing in model
1. I have to figure out how to get category which the article belongs.
art = Arts.objects.filter(translations__alias=pk)
art[0].cat.related_val[0] // I get master id
1.1. How to get many-to-many:
a = art[0].cat.all()
ctg = Arts.objects.filter(cat__translations__name=a[0])
57. To run all tests //$ python3 manage.py test my_appname.tests --verbosity 2 --parallel 2 // Django testin is not suit for url testing
58. Better use Selenium or Playwright for this purposes.
TODO:
registration
Session control
comments
Protect from links posting
app integration
social media integration
integrate testing
Search
Enable spell check on my TinyMCE