2024年4月11日木曜日

Django モデルフォームではModelでblank=Falseにするとrequired=Trueになる

Djangoのモデルからフォームを作りました。

forms.pyのほうでこんな感じで required=Trueにしました。

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['required'] = True

こうすると、inputにrequiredが追加されます。

このrequiredをテンプレートで判定するため以下のように

{% for field in form %}
    {% if field.required %}必須{% endif %}
{% endfor %}

とすればOKかと思ったら、field.required がどうしてもTrueになりません。

以下を参照すると {% if field.field.required %} にしろと書いてある。

Tell if a Django Field is required from template

それでも field.field.required はFalseのままでだめでした。

さらに以下を参照すると

Django: Make certain fields in a ModelForm required=False

you ought to add blank=True to the corresponding model

The documentation says

If the model field has blank=True, then required is set to False on the form field. Otherwise, required=True.

とありました。モデルのフィールドを blank=False にしないとテンプレートでは required=True 判定しないようです。

結論としては以下となります。

  • 必須にしたいモデルのフィールドを blank=False にする
  • テンプレートでは
    {% for field in form %}
        {% if field.field.required %}必須{% endif %}
    {% endfor %}
    のようにする。


2024年4月3日水曜日

ffmpeg 一括操作のコマンド (Windowsの場合)

ffmpeg 一括操作のコマンドのメモです。Windowsの例です。


複数のMP4ファイルから静止画を1枚ずつ保存する

> for %i in (./*.mp4) do ffmpeg -i ./%~ni.mp4 -ss 0 -t 1 -r 1 -f image2 ./%~ni.jpg

※この例は動画の0秒から1秒の間で1つの画像を保存するコマンド



音声の削除
> ffmpeg -i 入力ファイル名 -vcodec copy -an 出力ファイル名

音声の一括削除(no_soundフォルダ内に出力)
> for %i in (./*.mp4) do ffmpeg -i ./%~ni.mp4 -vcodec copy -an ./no_sound/%~ni.mp4

2023年12月5日火曜日

Python: 現在のディレクトリ取得と変更

現在のディレクトリを取得

import os

cwd = os.getcwd()

print(cwd)  # /Users/demo-user/documents/mydir


ディレクトリを変更

os.chdir('/Library')

cwd = os.getcwd()

print(cwd)  # /Library



2023年10月24日火曜日

.htaccess リダイレクト設定 ‐ ファイル名に半角スペースやカッコがある場合

Apacheサーバーにあるファイルのリダイレクト設定です。

ファイル名に半角スペースや半角カッコがあっため 500 Internal Server Errorが発生してディレクトリにアクセスできなくなってしまいます。

.htaccess 最初の設定 *このままだと500エラーが発生

RewriteEngine On
Rewriterule ^abc xyz.pdf$ https://example.com/abcxyz/ [L, R=301]
Rewriterule ^abc(123)xyz.pdf$ https://example.com/abcxyz/ [L, R=301]


ファイル名をクオーテーションマーク " で囲い(^と$の外側に記述)、半角カッコはバックスラッシュ \ でエスケープが必要でした。

.htaccess 修正後

RewriteEngine On
Rewriterule "^abc xyz.pdf$" https://example.com/abcxyz/ [L, R=301]
Rewriterule "^abc\(123\)xyz.pdf$" https://example.com/abcxyz/ [L, R=301]

2023年9月26日火曜日

正規表現で改行を含んだワイルドカード指定

([\s\S\n]*?) または ([\s\S\n]⁺?)

*は0個以上の一致、⁺は1個以上の一致

  • \s: 空白文字を表す。[ \t\n\r\f]と同じ
  • \S: 非空白文字を表す。[ \t\n\r\f]以外の一文字。
  • \n: 改行文字を表す。

参考: VS Codeで複数行に渡って正規表現を利用する - Qiita
https://qiita.com/birdwatcher/items/dee34a11619b11e1fe81

2023年9月22日金曜日

django-CMSでのチェック方法

django-CMS (https://www.django-cms.org)

$ python manage.py cms check

を実行すると保存されておらずorphanedになったものが発見される場合がある。
以下を実行して削除する。

$ python manage.py cms list plugins

$ python manage.py cms delete-orphaned-plugins


2023年8月10日木曜日

Python クロージャ―で文字列を連続して連結

Pythonでクロージャ―を使って文字列を連続して連結する方法です。
def add_string():
    string = ''
    def add_string_inner(new_string):
        nonlocal string
        string += new_string
        return string
    return add_string_inner
messages = add_string()

print(messages(''))     # 空白
print(messages('abc'))  # abc
print(messages('123'))  # abc123
print(messages('xyz'))  # abc123xyz