Advanced search
Evgenij LegotskojJune 1, 2022, 3:30 a.m.

DjangoDjango - Lesson 059. Saving the selected language in user settings

python, language, translation, django

In this article, I would like to show an example of how you can make a link on the site so that the user can switch between languages on the site.

But I will show a more advanced version of this functionality, namely saving the selected language in the user table, as well as redirecting the user to a page with the correct language that was selected by the user, if they are of course authorized. That is, if the user has set the German language for himself, then when going to the site via an English link, the site will automatically redirect the user to the page with the German language.

To do this, we need to add a language code field to the user model, I hope that everyone is already using their user model in Django instead of the default one.
Rewrite the standard Django language setup function, and also add a Middleware that will process the urls requested from the site.

Among other things, this functionality will be useful in order to generate letters with the correct language for registered users.

This article is based on Django 4 and may not be suitable for older versions of Django.

Evgenij LegotskojFeb. 8, 2022, 5:55 a.m.

DjangoDjango - Tutorial 055. How to write auto populate field functionality

field, Django, python, auto, Python

For a long time I wanted to write an article on how to write auto populate field functionality for a Django project. This is a very useful feature that allows you to change the content of other model fields in Django by setting a value to a field that uses auto populate.

First, why is it needed? - Such functionality allows you to reduce the size of the code in those places where you need to rewrite other fields of the object when they change. That is, for example, you do not have to redefine the save method each time in order to rewrite some field in case other fields of the object change. Also, using auto populate is basically a more advanced and neat way to manage data models in Django.
And also a similar approach can solve some problems and improve the site.

NomadJan. 28, 2022, 12:34 p.m.

PythonПитонячий модуль Scapy

python, scapy

Питонячий модуль

Всем привет.
Два дня пытаюсь нагуглить и ничего. Может кто сталкивался, поделитесь пожалуйста!
О проблеме:

есть некая виртуальная машина с Kali Linux (не спрашивайте почмеу Kali, проста был образ под рукой)
версия питона обновленна до 3.10.1 глобальн…

NomadJune 10, 2021, 1:51 p.m.

PythonPython ContextManager - непонятка

python, contextmanager

всем привет

пытаюсь разобраться в скрипте написанном не мною

суть скрипта:

есть база db.sqlite
есть запущенный elasticsearch сервак на локале - проверил, работает

скрипт забирает данные из базы и пушит их в базу elasticsearch

elasticsearch подготовлен к пушу,…

A
ArazFeb. 11, 2021, 11:43 a.m.

C++Подключить python к проекту на Qt C++

Qt, c++, python

Добрый день. Собственно интересует, как можно подключить и вызвать питоновский скрипт в своем приложении на С++?
Использую библиотеку распознавания голоса VOSK, написанную на Python. Приложение обрабатывается его и возвращает ответ - аля голосовой помощник.

На текущий момент, через …

progammistDec. 26, 2020, 4:29 p.m.

DjangoКак вывести статьи и профиль

Django, python, slug

Всем привет!

Вопрос такой, у меня есть мини-блог, есть статьи и профиль(страницы) пользователей.
Статьи я вывожу по адресу site/названиестатьи
Кабинет пользователя я хочу вывести по адресу site/юзернейм

views.py (статьей):

    def post_detail(request, slug):  
        …
---Oct. 5, 2020, 7:11 a.m.

Python 35 Ways to Remove Unnecessary Characters from a String in Python

python

Remove specific characters from the string


Let's use ' str.replace '

With the help of * str.replace *, we can change some characters to others. If we just want to remove some characters, then we simply replace them with an empty string. * str.replace () * will apply the replacement to all matches found.

s="Hello$ Python3$"
s1=s.replace("$", "")
print (s1)
# Результат: Hello Python3

If we can specify a limit for the number of matches, so as not to remove all characters.

s="Hello$ Python3$"
s1=s.replace("$", "", 1)
print (s1)
# Результат: Hello Python3$

With ' re.sub '

re. sub (pattern, repl, string, count=0, flags=0)

> Returns the string obtained by replacing the leftmost non-overlapping
> matches a pattern in a string to the value repl. If pattern matches
> not found, an unmodified string is returned
> - From Python documentation

If we want to remove characters, then we simply replace the matches with an empty string.

s="Hello$@& Python3$"
import re
s1=re.sub("[$|@|&]","",s)
print (s1)
# Результат: Hello Python3

s1=re.sub(“[$|@|&]”,””,s)

  • Template to replace → * “[$ | @ | &] ”*
    • [] * is used to define a set
    • $ | @ | & * → will search for $ or @ or &
  • Replace with an empty string
  • If the above characters are replaced found, then they are replaced with an empty string
Evgenij LegotskojMay 13, 2020, 4:42 a.m.

Python 3Python Image Recognition with TensorFlow and Keras

Keras, python, RuCaptcha, TensorFlow

Introduction

One of the most common uses of TensorFlow and Keras is in image recognition and classification. If you would like to learn how to use Keras for image classification or recognition, this article will teach you how to do it.

Definitions

If you do not understand the basic concepts of image recognition, it will be difficult for you to fully understand the main part of this article. Therefore, before we continue, let's define the terminology.

Said PyMay 6, 2020, 2:37 a.m.

Python 3How to Hide Firefox [selenium] in python

selenium, python

In this tutorial, we’ll learn how to Hide selenium firefox in python.

Said PyMay 6, 2020, 2:37 a.m.

Python 3How to Hide Firefox [selenium] in python

selenium, python

In this tutorial, we’ll learn how to Hide selenium firefox in python.

Card image cap
Pulsum Via

Project for travelers from EVILEG.

Go
Fornex

Let me recommend you a great European Fornex hosting.

Fornex has proven itself to be a stable host over the years.

For Django projects I recommend VPS hosting

Following the link you will receive a 5% discount on shared hosting services, dedicated servers, VPS and VPN

View Hosting
Share on social networks
Donate

The EVILEG project has switched to a non-commercial basis and will develop solely on the enthusiasm of the site creator, the enthusiasm of users, donations and the hosting referral system

Thank you for your support

Available ways to support the project

PayPal

PatreonYandex.MoneyMore
DP

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:10points,
  • Rating points-10
VS

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:0points,
  • Rating points-10
VS

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
Last comments
Ds

Android and QML - Adding Splash Screen

Интересен формат иконки, если это png, то как решается проблема scalability? не растягивается ли лого на китайфонах с 1280х2500? У меня просто сплеш скрин с градиентом и логотипом, и вот несколь…
p

Qt/C++ - Lesson 023. Moving QGraphicsItem on QGraphicsScene with mouse help

FIGURE Abdominopelvic regions. Zjuaqd https://newfasttadalafil.com/ - Cialis Cialis Recommendations for preparing children and adolescents for invasive cardiac procedures a statement…
KG

How to use nested forms in Django

Спасибо за полезную статью. Подскажите пожалуйста, что делать если нужно реализовать большее количество вложенных форм? Например если на модель Address ссылается fk другой модели, на котору…

Qt/C++ - Lesson 051. QMediaPlayer – simple audio player

Не думаю, QMediaPlayer в один поток проигрывает. Если вам нужно одновременное воспроизведение нескольких аудиоисточников, то вам нужна Bass audio library , насколько знаю, её обычно и…
AG

Qt/C++ - Lesson 051. QMediaPlayer – simple audio player

есть такая вообще возможность ?
Now discuss on the forum
AB

Sorting the added QML elements in the ListModel

I am writing an alarm clock in QML, I am required to sort the alarms in ascending order (depending on the date or time (if there are several alarms on the same day). I've done the sorting …

Изменение поведения QGroupBox при клике на его чекбокс

Я вынес виджеты вынес за пределы QGroupBox в итоге.

QSqlRelatipnalTabelModel Qt 4.8.1 как получить id внешней связи?

Есть еще принципиально другой вариант решить раз и навсегда вопрос с полей id внешней связи. Это форкнуть Qt 4.8.1 QSqlTableModel, то есть создать свою ветку развития. Например создадим кл…

Добавление AndroidManifest.xml в cmake

Добрый день. Как добавить AndroidManifest.xml в cmake? Это не работвет set(ANDROID_PACKAGE_SOURCE_DIR ${PROJECT_SOURCE_DIR}/android CACHE INTERNAL "")set(ANDROID_BUID_DIR ${CMAKE_C…
s

Событие wheelEvent для виджета QLineEdit

вот что получилось: gui.py from PyQt5 import QtCore, QtGui, QtWidgets class LineEdit(QtWidgets.QLineEdit): def wheelEvent(self, event): #print("_") delta = 1 if e…
About
Services
© EVILEG 2015-2022
Recommend hosting TIMEWEB