11

models.py:

class UserProfile(models.Model):

    photo = models.ImageField(upload_to = get_upload_file_name,
                              storage = OverwriteStorage(),
                              default = os.path.join(settings.STATIC_ROOT,'images','generic_profile_photo.jpg'),
                              height_field = 'photo_height',
                              width_field = 'photo_width')
    photo_height = models.PositiveIntegerField(blank = True, default = 0)
    photo_width = models.PositiveIntegerField(blank = True, default = 0)

ビュー.py:

def EditProfile(request):

    register_generator()
    source_file = UserProfile.objects.get(user = request.user).photo

    args = {}
    args.update(csrf(request))
    args.update({'source_file' : source_file})

私のテンプレートのどこかに:

{% generateimage 'user_profile:thumbnail' source=source_file %}

エラーが表示されます: UserProfile 一致するクエリが存在しません。

この行で:

source_file = UserProfile.objects.get(user = request.user).photo

問題は、ImageField のデフォルト属性が機能していないことです。したがって、オブジェクトはモデル内に作成されません。この属性を適切に使用するにはどうすればよいですか? この属性を省略すると、オブジェクトはエラーなしで作成されます。絶対パスまたは相対パスを渡す必要がありますか? django-imagekit を使用して、画像を表示する前にサイズを変更しています: http://django-imagekit.readthedocs.org/en/latest/

4

1 に答える 1

15

デフォルト属性を定義しない場合、画像のアップロードは正常に機能しますか? 自分の django プロジェクトに ImageField を実装したとき、デフォルトの属性を使用しませんでした。代わりに、デフォルトの画像へのパスを取得するために次のメソッドを作成しました。

def image_url(self):
"""
Returns the URL of the image associated with this Object.
If an image hasn't been uploaded yet, it returns a stock image

:returns: str -- the image url

"""
    if self.image and hasattr(self.image, 'url'):
        return self.image.url
    else:
        return '/static/images/sample.jpg'

次に、テンプレートで、次のように画像を表示します。

<img src="{{ MyObject.image_url }}" alt="MyObject's Image">

編集:簡単な例

views.py で

def ExampleView(request):
    profile = UserProfile.objects.get(user = request.user)
    return render(request, 'ExampleTemplate.html', { 'MyObject' : profile } )

次に、テンプレートにコードを含めます

<img src="{{ MyObject.image_url }}" alt="MyObject's Image">

画像を表示します。

また、「UserProfile 一致するクエリが存在しません」というエラーについても同様です。UserProfile モデルのどこかに User モデルへの外部キー関係を定義したと思いますよね?

于 2014-03-22T19:27:08.297 に答える