2012-05-30 2 views
4

У меня есть модель и форма (forms.ModelForm), в которой у меня есть ImageField. Модель напоминает:Django ModelForm ImageField

class Business(models.Model): 
    business_name = models.CharField(max_length=128) 
    . 
    . 
    business_image = ImageField(
     max_length=128, 
     upload_to=upload_business_image_handler, 
     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) 
    . 
    . 

сопутствующая форма:

class BusinessForm(forms.ModelForm): 
    def __init__(self, data=None, files=None, branch_list = None, country_list = None, *args, **kwargs): 
     super(BusinessForm, self).__init__(data, *args, **kwargs) 
     # create the MultipleChoiceField choice_list based on language 
     self.fields['branch'].choices = branch_list 
     self.fields['country'].choices = country_list 
     self.postdata = data 
     self.files = files 

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

    #business_image = forms.ImageField(widget=forms.ClearableFileInput()) 

Последняя строка в форме комментируется, потому что forms.ClearableFileInput() является виджет по умолчанию для FileFields и ImageFields.

Теперь, когда эта форма используется для редактирования существующей записи изображения в шаблоне отображаются следующим образом:

Currently: <image_url> 
Change: <browse_button> 

Я хотел бы изменить текстовые метки «В настоящее время» и «Change» и вместо показать image_url Я хотел бы показать изображение.

Конечно, я могу скопировать и изменить код класса ClearableFileInput (FileInput) ', найденного в' site-packages/django/forms/widgets.py ', но мне интересно, если это способ сделать это.

Любая помощь или предложение оценены.

Теперь я посмотрел на код «класса ClearableFileInput (FileInput)»

ответ

1

Я бы поставил это в виде шаблона

{% if business.business_image %} 
    <img src="{{ business.business_image.url }}" title="{{ business.business_name}}" /> 
{% endif %} 
+0

Да, который отобразил бы изображение в t эмблема, но 2 пункта, о которых я упоминал, в настоящее время: и Изменить: все равно будет в шаблоне. – Henri

3

Вот мое решение одной и той же проблемы.

from django.utils.safestring import mark_safe 
from django.utils.html import escape, conditional_escape 
from django.utils.encoding import force_unicode 
from django.forms.widgets import ClearableFileInput, Input, CheckboxInput 

class CustomClearableFileInput(ClearableFileInput): 

    def render(self, name, value, attrs=None): 
     substitutions = { 
      #uncomment to get 'Currently' 
      'initial_text': "", # self.initial_text, 
      'input_text': self.input_text, 
      'clear_template': '', 
      'clear_checkbox_label': self.clear_checkbox_label, 
      } 
     template = '%(input)s' 
     substitutions['input'] = Input.render(self, name, value, attrs) 

     if value and hasattr(value, "url"): 
      template = self.template_with_initial 
      substitutions['initial'] = ('<img src="%s" alt="%s"/>' 
             % (escape(value.url), 
              escape(force_unicode(value)))) 
      if not self.is_required: 
       checkbox_name = self.clear_checkbox_name(name) 
       checkbox_id = self.clear_checkbox_id(checkbox_name) 
       substitutions['clear_checkbox_name'] = conditional_escape(checkbox_name) 
       substitutions['clear_checkbox_id'] = conditional_escape(checkbox_id) 
       substitutions['clear'] = CheckboxInput().render(checkbox_name, False, attrs={'id': checkbox_id}) 
       substitutions['clear_template'] = self.template_with_clear % substitutions 

     return mark_safe(template % substitutions) 

, а затем просто использовать расширенный виджет:

business_image = forms.ImageField(widget=CustomClearableFileInput()) 
0

Это моя версия из imageInput, который показывает изображение и не позволяет для очистки изображения

Просто надо указать в поле вида widget=NonClearableImageInput()

from django.forms.widgets import FileInput 
from django.utils.html import conditional_escape 
from django.utils.safestring import mark_safe 

class NonClearableImageInput(FileInput): 
    def render(self, name, value, attrs=None): 
     template = '%(input)s' 
     data = {'input': None, 'url': None} 
     data['input'] = super(NonClearableImageInput, self).render(name, value, attrs) 

     if hasattr(value, 'url'): 
      data['url'] = conditional_escape(value.url) 
      template = '%(input)s <img src="%(url)s">' 

     return mark_safe(template % data) 
Смежные вопросы