jupyter: Django

Jupyter: Django 準備 django_extensions , notebookを入れておく settgins.py: 1 INSTALLED_APPS += ['django_extensions'] VSCode VSCodeでJupyterのPythonランタイムを選んでから以下を実行する 環境変数で、DJANGO_ALLOW_ASYNC_UNSAFE=true をセットしておく(.envとか) 1 2 3 4 5 6 import sys, os, django BASE_DIR = "path_ot_manage_py" sys.path.insert(0, BASE_DIR) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") django.setup() リモートサーバー autossh でポートフォワード PCの 8.8.8.8 -> リモート(EC2とか)の 8.8.8.8 にフォワードする: 1 autossh -M 0 -F .secrets/ssh.ec2.conf server -N -L 8888:localhost:8888 -4 カーネル起動 1 DJANGO_ALLOW_ASYNC_UNSAFE=true python manage.py shell_plus --notebook URLが表示されるので、ブラウザでアクセスする ...

2023年5月5日 · 1 分

Django: SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async

Jupyter: Django: SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async このエラーは、asyncコンテキストから同期的なコードを呼び出そうとした場合に発生するエラーです。 async-unsafeなコードを呼び出す場合は、asyncコンテキストからではなく、自分自身の同期関数で書き、それをasgiref.sync.syncを使用して呼び出すように修正する必要があります¹。 ¹: Django: SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. - Stack Overflow ソース: Bing との会話 2023/5/4 (1) Django: SynchronousOnlyOperation: You cannot call this …. https://stackoverflow.com/questions/61926359/django-synchronousonlyoperation-you-cannot-call-this-from-an-async-context-u. (2) django.core.exceptions.SynchronousOnlyOperation after …. https://github.com/django/channels/issues/1464. (3) python - Django channels Async Websocket throwing Error …. https://stackoverflow.com/questions/63892884/django-channels-async-websocket-throwing-error-while-trying-to-use-database-quer. (4) Django channel occasionally gets error “cannot call this from …. https://stackoverflow.com/questions/69239657/django-channel-occasionally-gets-error-cannot-call-this-from-an-async-context. (5) python - Getting SynchronousOnlyOperation error Even after …. https://stackoverflow.com/questions/63149616/getting-synchronousonlyoperation-error-even-after-using-sync-to-async-in-django. DJANGO_ALLOW_ASYNC_UNSAFE 環境変数を使用することで、非同期コンテキストで SynchronousOnlyOperation エラーが発生した場合に警告を無効にすることができます¹。 ...

2023年5月4日 · 1 分

factory_boy: SubFactory

factory_boy: SubFuctory で ForeignKeyフィールドを初期化する factory_boy はテストデータを簡単に作るためのライブラリです²。ForeignKey フィールドのインスタンスのデフォルトを定義するには、SubFactory を使う方法があります¹⁴。例えば、以下のように書けます。 1 2 3 4 5 6 7 8 class PhoneContactFactory(factory.django.DjangoModelFactory): class Meta: model = models.PhoneContact class CoopFactory(factory.django.DjangoModelFactory): class Meta: model = models.Coop phone = factory.SubFactory(PhoneContactFactory) この場合、CoopFactory を使って Coop インスタンスを作ると、PhoneContactFactory も使って PhoneContact インスタンスを作り、そのインスタンスを Coop の phone フィールドにセットします。 もしくは、SelfAttribute を使う方法もあります⁴。例えば、以下のように書けます。 1 2 3 4 5 6 7 8 class SubtitlesFactory(factory.django.DjangoModelFactory): class Meta: model = models.Subtitles class RecordingFactory(factory.django.DjangoModelFactory): class Meta: model = models.Recording subtitles = factory.SubFactory(SubtitlesFactory, language=factory.SelfAttribute('..language')) この場合、RecordingFactory を使って Recording インスタンスを作るときに language パラメータを指定すると、その値が SubtitlesFactory の language パラメータにも渡されます。 ...

2023年4月30日 · 2 分

DRF: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list

DRF: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list ViewSetの queryset で order_by を明示的に指定すること I see. Django REST framework also supports pagination for large result sets, but you need to specify a default pagination class and a page size in your settings.py file¹. Alternatively, you can set the pagination_class attribute for each viewset individually⁴. However, you still need to order your queryset by some field, otherwise you will get the same warning as before²³. You can use the order_by method on your queryset or the ordering attribute on your viewset¹. For example: ...

2023年4月29日 · 1 分

Django MPTT: values で tree_id が SELECT されてしまう

Django MPTT: values で tree_id が SELECT されてしまう 仕様である django-mptt の TreeQuerySet で values コールすると SQL に tree_id が追加されているのは、django-mptt がツリー構造を管理するために必要なカラムだからです²。tree_id は、同じツリーに属するノードに同じ値を持ちます²。例えば、以下のようなモデルがあるとします。 1 2 3 4 5 6 7 8 9 from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] このとき、以下のように values をコールすると、SQL に tree_id が追加されます²。 ...

2023年4月28日 · 1 分

Django: Template: QuerySetの指定したindexのインスタンスの参照

Django: Template: QuerySet の指定した index のインスタンスの参照 配列ではないので、数値でインデクシングできない {{ e.expenseitem_set.0 }} {# NG #} 1件目, 最後 {{ e.expenseitem_set.first.account_name }} {{ e.expenseitem_set.last.account_name }} テンプレートフィルター 1 2 3 4 5 6 7 from django import template register = template.Library() @register.filter def index(queryset, i): return queryset[i] 1 {% load expenses %} {{ e.expenseitem_set|index:1 }} QuerySet のインクシング list のように -1 などの Python のインデクシングはできない (するには list(queryset) で list に変換する)

2023年4月27日 · 1 分

DRF: Userを所属グループで検索

django-filters: Userを所属グループで検索 Django REST Frameworkとdjango-filterを使って、Userが所属しているGroupを複数指定して検索することはできます。 以下のように、django-filter.FilterSetを継承したフィルタセットを定義し、filters.ModelMultipleChoiceFilterを使って、Userが所属しているGroupを複数指定することができます。 1 2 3 4 5 6 7 8 9 10 11 12 13 from django.contrib.auth.models import User, Group import django_filters class UserFilter(django_filters.FilterSet): groups = django_filters.ModelMultipleChoiceFilter( field_name='groups__name', to_field_name='name', queryset=Group.objects.all() ) class Meta: model = User fields = ['username', 'groups'] 上記の例では、Userモデルに対するフィルタセットを定義しています。groupsフィールドには、django_filters.ModelMultipleChoiceFilterを使って、Userが所属しているGroupを複数指定することができます。field_nameには、Userモデルのgroups__nameフィールドを指定し、to_field_nameには、Groupモデルのnameフィールドを指定しています。 ...

2023年4月23日 · 1 分

Python: モジュールの実装パス

モジュール名からファイルを見つける Pythonのモジュール名が与えられた時、そのモジュールの実装されているファイルのパスを調べるには、以下のようにします。 1 2 3 4 5 6 7 import importlib.util def get_module_path(module_name): spec = importlib.util.find_spec(module_name) if spec is None: return None return spec.origin 上記のように、importlib.util.find_spec()関数を使って、モジュール名からspecオブジェクトを取得し、spec.origin属性を参照することで、モジュールが実装されているファイルのパスを取得することができます。 ソース: Bing との会話 2023/4/23 (1) 6. モジュール — Python 3.11.3 ドキュメント. https://docs.python.org/ja/3/tutorial/modules.html. (2) Pythonで独自モジュールのディレクトリパスを通す方法 …. https://lightgauge.net/language/python/add-module-path. (3) 【Python】パッケージ・モジュールの検索と import - Qiita. https://qiita.com/shinsa82/items/5004a3ea63594f20190d. Djangoのアプリケーションの場合 1 2 3 4 5 6 7 8 from django.apps import apps class Def: @property def path(self): app_label = self.__module__.split(".")[0] conf = apps.get_app_config(app_label) return conf.path

2023年4月23日 · 1 分

Django: User ログインシグナル

Django: User ログイン ログインシグナル Djangoでログインした時のイベントをシグナルで受け取る方法については、Djangoの公式ドキュメントに詳しく記載されています¹。以下のように、django.contrib.auth.signals.user_logged_inシグナルを使用して、ログイン時に実行する関数を定義し、receiver()デコレーターでシグナルを受信する関数を登録します。 1 2 3 4 5 6 7 from django.contrib.auth.signals import user_logged_in from django.dispatch import receiver @receiver(user_logged_in) def user_logged_in_callback(sender, request, user, **kwargs): # ログイン時に実行する処理 pass このように、シグナルを使用することで、ログイン時に任意の処理を実行することができます。 ソース: Bing との会話 2023/4/21 (1) 「超簡単」Djangoでログインページの実装 - Qiita. https://qiita.com/Yuji-Sakata0110/items/3722fa651e02eafc4d01. (2) 【Django】ログイン・ログアウト機能の実装 - Qiita. https://qiita.com/onishi_820/items/c69ebb6a4e34da0f34d4. (3) Django パスワード試行回数ロックとランダムかつ有効期限付き …. https://qiita.com/startours777/items/5b1fc415e047a2044129.

2023年4月21日 · 1 分

半角カナ文字

半角カナ文字 Pythonで半角カナ文字かどうかを判定するには、正規表現を使う方法があります。⁴⁶ 例えば、次のような関数を定義して、文字列が半角カナだけで構成されているかどうかをチェックできます。 1 2 3 4 import re def is_hankaku_kana(s): return re.match(r"^[ヲ-゚]+$", s) is not None この関数は、文字列sが半角カナの範囲(ヲから゚)にマッチするかどうかを判定します。⁶ 他の言語(JavaScriptやC#など)でも同様の方法が使えます。¹² ソース: Bing との会話 2023/4/18 (1) python 正規表現を使った文字列チェック【ひらがな・カタカナ …. https://qiita.com/mocha_xx/items/00c5a968f7069d8e092c アクセス日時 2023/4/18. (2) Pythonで正規表現を使って数値/英字チェックを実装する (コピペ …. https://www.sukerou.com/2018/12/python.html アクセス日時 2023/4/18. (3) [JavaScript] 全角カナ、半角カナの判定を行う方法 - YoheiM .NET. https://www.yoheim.net/blog.php?q=20191105 アクセス日時 2023/4/18. (4) [C#共通関数] 半角カナチェックFunction - C#ちょこっとリファレンス. https://csharp.programmer-reference.com/function-check-han-kana/ アクセス日時 2023/4/18. (5) 文字がひらがなか、カタカナか、漢字か、英数字か調べる - .NET …. https://dobon.net/vb/dotnet/string/ishiragana.html アクセス日時 2023/4/18. (6) python - 半角数字・文字のチェック方法 - スタック・オーバーフロー. https://ja.stackoverflow.com/questions/90953/%E5%8D%8A%E8%A7%92%E6%95%B0%E5%AD%97-%E6%96%87%E5%AD%97%E3%81%AE%E3%83%81%E3%82%A7%E3%83%83%E3%82%AF%E6%96%B9%E6%B3%95 アクセス日時 2023/4/18. 半角カナ文字を判定するPYPIパッケージはありますか? 半角カナ文字を判定する専用のPYPIパッケージは見つかりませんでしたが、標準ライブラリのunicodedataモジュールを使うことができます。¹ ...

2023年4月18日 · 2 分