django session

Sessionのユーザーの取得 Djangoでセッションレコードがどのユーザーのものかを判定するには、以下のようにします。 1 2 3 4 5 6 7 8 from django.contrib.sessions.models import Session from django.contrib.auth.models import User for session in Session.objects.all(): uid = session.get_decoded().get('_auth_user_id') if uid: user = User.objects.get(id=uid) print(user.username) 参考文献: Django ドキュメント | セッションの使いかた ソース: Bing との会話 2023/5/30 (1) セッションの使いかた | Django ドキュメント | Django. https://docs.djangoproject.com/ja//2.2/topics/http/sessions/. (2) 【Django】ログイン判定機能の実装方法を実例付きで徹底解説. https://itc.tokyo/django/dynamic-links-by-user-info/. (3) Djangoで現在ログインしているユーザーのユーザーIDを取得する方法. https://qastack.jp/programming/12615154/how-to-get-the-currently-logged-in-users-user-id-in-django. SessionStoreをつかう 1 2 3 4 5 6 7 from django.contrib.sessions.backends.db import SessionStore key = "3gsbhdfm4g2uyyieaaxl1omor2p5f1on" store = SessionStore(session_key=key) store["ssout_required"] = True store.save()

2023年5月30日 · 1 分

DRF: Content Negotiation

DRF: Content Negotiation DefaultContentNegotiation content_negotiation_classをカスタマイズするには、以下のようにします。 1 2 3 4 5 6 from rest_framework.negotiation import DefaultContentNegotiation class MyContentNegotiation(DefaultContentNegotiation): def select_renderer(self, request, renderers, format_suffix=None): # ここに処理を書きます。 pass 上記の例では、DefaultContentNegotiationを継承しています。 select_renderer()メソッドには、レンダラーを選択するための処理を書きます。 このメソッドは、リクエストオブジェクト、レンダラーのリスト、およびフォーマットサフィックスを引数として受け取ります。 ソース: Bing との会話 2023/5/12 (1) Content negotiation - Django REST framework. https://www.django-rest-framework.org/api-guide/content-negotiation/. (2) Django REST Framework - Content negotiation - HTTPは …. https://runebook.dev/ja/docs/django_rest_framework/api-guide/content-negotiation/index. (3) Django REST framework カスタマイズ方法 - チュートリアルの補足. https://qiita.com/okoppe8/items/c58bb3faaf26c9e2f27f. ViewSetでの設定 ViewSetごとにcontent_negotiation_classを設定することができます。 ...

2023年5月12日 · 1 分

pandas: カラム連結

pandas: カラム連結 pandasで数値カラム同士を文字列に変換するには、 df['新しい列名'] = df['数値カラム1名'].astype(str) + df['数値カラム2名'].astype(str) と書くことができます。 例えば、以下のようになります。 1 2 3 4 5 import pandas as pd df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) df['C'] = df['A'].astype(str) + df['B'].astype(str) print(df) 出力: A B C 0 1 3 13 1 2 4 24 以上のように、df['新しい列名'] = df['数値カラム1名'].astype(str) + df['数値カラム2名'].astype(str) を使って、2つの数値の列を文字列に変換してから連結して新しい列を追加することができます。 ソース: Bing との会話 2023/5/11 (1) python - dataframe内の数値から文字列に変換する方法 - スタック …. https://ja.stackoverflow.com/questions/74518/dataframe%e5%86%85%e3%81%ae%e6%95%b0%e5%80%a4%e3%81%8b%e3%82%89%e6%96%87%e5%ad%97%e5%88%97%e3%81%ab%e5%a4%89%e6%8f%9b%e3%81%99%e3%82%8b%e6%96%b9%e6%b3%95. (2) 【Pandas】DataFrameから文字列と数値データのcolumnを分ける. https://mochablog.org/pandas-saparate-numerical-col/.

2023年5月11日 · 1 分

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 分