在這裏一個小竅門後,在那裏我終於能夠得到這個工作。
Models.py
class ImageMedia(models.Model):
caption = models.CharField(max_length=64)
picture = models.ImageField(upload_to='image_media', blank=True)
class SplashScreen(models.Model):
title = models.CharField(max_length=25)
text = models.TextField()
background = models.ForeignKey(Background)
button = models.ForeignKey(Button)
url = models.URLField()
picture = models.ForeignKey(ImageMedia)
def splash_image(self):
return '<img id="media_image" src="{0}{1}" height="150px"/><p id="media_caption">Caption</p> '.format(
settings.MEDIA_URL, '')
splash_image.allow_tags = True
def __str__(self):
return self.title
views.py
from django.contrib.auth.decorators import login_required
import json
@login_required
def get_picture_media(request):
if request.method == 'GET':
media_id = request.GET['media_id']
if media_id:
media = ImageMedia.objects.get(id=int(media_id))
if media:
media_data = {'media_url': media.picture.url, 'media_caption': media.caption}
return HttpResponse(json.dumps(media_data))
Admin.py
class SplashScreenAdmin(admin.ModelAdmin):
list_display = ('title', 'text', 'background', 'button',)
search_fields = ('title', 'text')
list_filter = ('background', 'button')
raw_id_fields = ('picture',)
fields = ('title', 'text', 'background', 'button', 'url', 'picture', 'splash_image')
readonly_fields = ['splash_image']
class Media:
js = ("js/media-render.js",)
admin.site.register(SplashScreen, SplashScreenAdmin)
JS /媒體render.js
function media_render() {
var id_picture = document.getElementById('id_picture').value;
var media_url = '';
var media_caption = '';
$.get(document.location.origin + '/get_picture_media/', {media_id: id_picture},
function(data){
data = JSON.parse(data);
media_url = data['media_url'];
media_caption = data['media_caption'];
document.getElementById('media_image').src = media_url;
document.getElementById('media_caption').innerHTML = media_caption;});
};
window.onfocus = media_render;
document.getElementById('id_picture').onchange = media_render;
這樣,我可以隨時更新我的圖像,每當我更改原始ID,我也可以獲得標題。隨着schillingt我分開JS那麼一點點的代碼現在有點整潔
最終結果:
您是否嘗試過在指定領域的'''help_text'''參數? https://docs.djangoproject.com/en/dev/ref/models/fields/#help-text – schillingt 2014-10-07 01:48:09
我也想從數據模型中獲取標題。所以,如果它是圖片,我可以得到圖片名稱或圖片網址。我不認爲help_text可以檢索對象數據。 – Nameless 2014-10-07 01:50:47
你說得對。這是我的錯誤。你必須考慮自定義一個表單域來做你想要的。 – schillingt 2014-10-07 01:54:16