2012-05-30 9 views
4

ImageField가있는 모델과 양식 (forms.ModelForm)이 있습니다. 이 모델은 유사합니다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) 
    . 
    . 

수행 폼 : forms.ClearableFileInput()가 FileFields 및 ImageFields의 기본 위젯이기 때문에

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()) 

형태의 마지막 줄은 주석. 이 양식 템플릿에있는 이미지로 표시되는 기존의 레코드를 편집하는 데 사용됩니다 이제

은 다음과 같습니다

Currently: <image_url> 
Change: <browse_button> 

나는 '현재'텍스트 레이블과 '변화'대신을 변경하려면 image_url을 보여 주며 이미지를 보여주고 싶습니다.

물론 'site-packages/django/forms/widgets.py'에있는 'ClearableFileInput (FileInput)'코드를 복사하고 수정할 수는 있지만이를 수행하는 방법인지 궁금합니다.

도움이나 의견을 보내 주시면 감사하겠습니다.

지금 나는의 코드 '클래스 ClearableFileInput (fileinput 함수)'나는 템플릿 양식

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

답변

1

살펴 보았다.

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) 

후 바로 확장 된 위젯 사용이 이미지를 표시하고 이미지를 삭제를 허용하지 않는 imageInput의 나의 버전은

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

예 emplate하지만 내가 언급 한 2 가지 항목 : 현재 : 및 변경 : 은 여전히 ​​템플릿에 있습니다. – Henri

3

여기에 같은 문제에 대한 내 솔루션은이 점을 넣어 것

0

입니다

단지 지정해야 해당 필드의 양식 클래스에서 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) 
관련 문제