3

次のモデルを含む django アプリがあります。

class Business(models.Model, GetDistance):
    business_name = models.CharField(max_length=128)
    .
    user = models.ForeignKey(User)
    .
    media_dir = models.CharField(max_length=256, blank=True)
    .
    business_image = models.ImageField(max_length=128, upload_to=upload_business_image_handler, blank=True, height_field='business_image_height', width_field='business_image_width')

    business_image_height = models.IntegerField(blank=True, null=True)
    business_image_width = models.IntegerField(blank=True, null=True)

次に、「ビジネス」モデルで使用されるアップロード ハンドラも定義しました。

def upload_business_image_handler(instance, filename):
    # determine the upload path
    .
    return file_path

いくつかのウィジェットを使用して入力フィールドのデフォルトのレンダリングを変更するフォームがあります。

business_name = forms.CharField(widget=forms.TextInput(attrs={'size':'50', 'class': 'address'}), required=True)

フォームでは business_image フィールドを指定していないため、モデルのデフォルトが使用されます。テンプレートのフォームには次のものがあります。

<form enctype="multipart/form-data" method="POST" action="">{% csrf_token %}

ビューコードには次が含まれます。

business_form = BusinessForm(request.POST, request.FILES, auto_id='id_registration_%s', branch_list = branch_list, country_list = country_list)

フォームにデータを入力し、business_image フィールドの画像を選択すると、すべてが期待どおりに機能するようになりました。ファイルの名前はビジネス オブジェクトにあり、ファイルは「upload_business_image_handler」によって決定されるディレクトリにアップロードされます。ただし、business_imageフィールドを次のように変更すると:

business_image = models.ImageField(max_length=128, upload_to=upload_business_image_handler, height_field='business_image_height', width_field='business_image_width')

つまり、「blank=True」オプションを削除すると、business_image フォーム フィールドで画像を選択しても、常に「このフィールドは必須です」というエラーが表示されます。

ビューに「assert False」を挿入すると、エラーが表示されますが、ファイル名とファイル オブジェクトも表示されるため、エラー メッセージがわかりません。

4

0 に答える 0