How do I show the error to the user when initializing the Django form?
I'm trying to do the following. The form should upload a text file. If it is not present, the form should not be loaded. An error should appear instead.
class SemanticAiForm(forms.Form):
semantic_folder = configurate.AI_DATA_FOLDER
semantic_files = 'ai_openai_fresh_news.txt'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
semantic = self.get_semantic()
if semantic is None:
self.add_error(NON_FIELD_ERRORS, 'No data')
else:
self.fields['order'] = forms.CharField(widget=forms.Textarea())
self.fields['order'].initial = semantic.system_content
def get_semantic(self) -> Union[SemanticTxt, None]:
"""
Получает объект SemanticTxt с прочитанным файлом параметрической
конфигурации.
"""
try:
filepath = os.path.join(self.semantic_folder, self.semantic_files)
semantic = read_semantic(filepath)
except exception.SemanticError:
return
return semantic
If there is a file, everything is fine. If there is no file, on the contrary. Django reports:
'SemanticAiForm' object has no attribute 'cleaned_data'
I'm trying to do something else. If there is no file, display an error in the template. And don't show the form. What am I doing wrong?
UPDATE
class RustpdAdminSite(admin.AdminSite):
"""
Переопределение админ-части создаёт пространство для творчества.
"""
def get_urls(self):
urls = super().get_urls()
custom_urls = [
path('semantic-ai/',
self.admin_view(views_admin.SemanticAiGPT.as_view(
admin_context=self.each_context)
),
name='semantic'),
]
return custom_urls + urls
The view function is called via views_admin. Perhaps it matters?
Update the form class as follows:
class SemanticAiForm(forms.Form): semantic_folder = configurate.AI_DATA_FOLDER semantic_files = 'ai_openai_fresh_news.txt'
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.is_valid_file = True semantic = self.get_semantic() if semantic is None: self.is_valid_file = False else: self.fields['order'] = forms.CharField(widget=forms.Textarea()) self.fields['order'].initial = semantic.system_content def get_semantic(self) -> Union[SemanticTxt, None]: try: filepath = os.path.join(self.semantic_folder, self.semantic_files) semantic = read_semantic(filepath) except exception.SemanticError: return None return semantic def is_bound(self): return super().is_bound() and self.is_valid_file def is_valid(self): if not self.is_valid_file: return False return super().is_valid()
Update your view as follows:
def your_view(request): form = SemanticAiForm() if form.is_valid_file: if request.method == 'POST': form = SemanticAiForm(request.POST) if form.is_valid(): # Your form processing code pass else: error_message = "File not found or couldn't be read." return render(request, 'your_template.html', {'error_message': error_message})
return render(request, 'your_template.html', {'form': form})
Update your template as follows:
{% if error_message %} {{ error_message }}
{% else %} {% csrf_token %} {{ form.as_p }} Submit {% endif %}