@nurzhannogerbek

NameError: global name 'Name' is not defined?

Здравствуйте, помогите пожалуйста решить следующую проблему.

Есть форма создания новой записи с полем для загрузки файла. По умолчанию Django использует для этого поля виджет ClearableFileInput. Я решил кастомизировать виджет, все отображается нормально при открытии формы, но при попытки сохранить (submit) вылетает ошибка. Что я пропустил?

models.py:
class Document(models.Model):
    src = models.FileField(max_length=255, upload_to='documents/', blank=True, null=True, validators=[validate_file_extension])


forms.py:
class DocumentCreateForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ('src',)
        widgets = {
            'src': CustomClearableFileInput,
        }

    def __init__(self, *args, **kwargs):
        super(DocumentCreateForm, self).__init__(*args, **kwargs)
        self.fields['src'].widget.attrs = {
            'accept':'.pdf, .zip, .rar, .doc, .docx, .rtf',
            'id': 'src',
        }


widgets.py:
from django.forms.widgets import FileInput
from django.utils.translation import gettext_lazy as _

__all__ = (
    'FileInput', 'CheckboxInput'
)

class CustomClearableFileInput(FileInput):
    clear_checkbox_label = ''
    input_text = ''
    initial_text = _('Текущий файл')
    template_name = 'documents/custom_clearable_file_input.html'

    def clear_checkbox_name(self, name):
        """
            Given the name of the file input, return the name of the clear checkbox input.
        """
        return name + '-clear'

    def clear_checkbox_id(self, name):
        """
            Given the name of the clear checkbox input, return the HTML id for it.
        """
        return name + '_id'

    def is_initial(self, value):
        """
            Return whether value is considered to be initial value.
        """
        return bool(value and getattr(value, 'url', False))

    def format_value(self, value):
        """
            Return the file object if it has a defined url attribute.
        """
        if self.is_initial(value):
            return value

    def get_context(self, name, value, attrs):
        context = super(CustomClearableFileInput, self).get_context(name, value, attrs)
        checkbox_name = self.clear_checkbox_name(name)
        checkbox_id = self.clear_checkbox_id(checkbox_name)
        context['widget'].update({
            'checkbox_name': checkbox_name,
            'checkbox_id': checkbox_id,
            'is_initial': self.is_initial(value),
            'input_text': self.input_text,
            'initial_text': self.initial_text,
            'clear_checkbox_label': self.clear_checkbox_label,
        })
        return context

    def value_from_datadict(self, data, files, name):
        upload = super(CustomClearableFileInput, self).value_from_datadict(data, files, name)
        if not self.is_required and CheckboxInput().value_from_datadict(
                data, files, self.clear_checkbox_name(name)):

            if upload:
                # If the user contradicts themselves (uploads a new file AND checks the "clear" checkbox).
                # We return a unique marker object that FileField will turn into a ValidationError.
                return FILE_INPUT_CONTRADICTION
            # False signals to clear any existing value, as opposed to just None
            return False
        return upload

    def use_required_attribute(self, initial):
        return super(CustomClearableFileInput, self).use_required_attribute(initial) and not initial

    def value_omitted_from_data(self, data, files, name):
        return (
            super(CustomClearableFileInput, self).value_omitted_from_data(data, files, name) and
            self.clear_checkbox_name(name) not in data
        )


custom_clearable_file_input.html:
{% load i18n %}
{% if widget.is_initial %}
	<div class="alert alert-info" role="alert" id="current-file-info">
		<i class="fa fa-file-text-o"></i>&nbsp;<span>{{ widget.initial_text }}:</span>
		<a href="{{ widget.value.url }}">{{ widget.value }}</a>
		{% if not widget.required %}
			<input type="checkbox" name="{{ widget.checkbox_name }}" id="{{ widget.checkbox_id }}"/>
			<label for="{{ widget.checkbox_id }}">{{ widget.clear_checkbox_label }}</label>
		{% endif %}
	</div>
{% endif %}
<div class="input-group" id="file-field-document">
	<input type="text" disabled="disabled" class="form-control" id="file-field-file-name">
	<span class="input-group-btn">
		<div class="btn btn-default" id="file-field-clear-btn" style="display: none;">
			<i class="fa fa-times"></i>
			<span>{% trans 'Очистить' %}</span>
		</div>
		<div class="btn btn-default" id="file-field-input">
			<i class="fa fa-file-text-o"></i>
			<span id="file-field-input-title">{% trans 'Загрузить файл' %}</span>
			<input type="{{ widget.type }}" name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %} />
		</div>
	</span>
</div>


views.py:
class DocumentCreate(CreateView):
    template_name = 'documents/create_document.html'
    form_class = DocumentCreateForm

    def get(self, request, *args, **kwargs):
        data = dict()
        context = {
            'document_create_form': DocumentCreateForm(),
        }
        data['html_form'] = render_to_string('documents/create_document.html', context, request=request)
        return JsonResponse(data)

    def form_valid(self, form):
        form.save()
        data = dict()
        data['form_is_valid'] = True
        context = {
            'documents': Document.objects.all()
        }
        data['html_documents'] = render_to_string('documents/documents.html', context, request=self.request)
        return JsonResponse(data)


ERROR:
Traceback (most recent call last):
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/views/generic/edit.py", line 217, in post
    return super(BaseCreateView, self).post(request, *args, **kwargs)
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/views/generic/edit.py", line 182, in post
    if form.is_valid():
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/forms/forms.py", line 183, in is_valid
    return self.is_bound and not self.errors
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/forms/forms.py", line 175, in errors
    self.full_clean()
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/forms/forms.py", line 384, in full_clean
    self._clean_fields()
  File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/forms/forms.py", line 396, in _clean_fields
    value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
  File "/Applications/Projects/web/my_project/documents/widgets.py", line 60, in value_from_datadict
    if not self.is_required and CheckboxInput().value_from_datadict(
NameError: global name 'CheckboxInput' is not defined
  • Вопрос задан
  • 844 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы