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?

New contributor

Schindler7 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

4

  1. 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()
    
  2. 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})
    
  3. Update your template as follows:

    {% if error_message %}
    {{ error_message }}

    {% else %}

    {% csrf_token %}
    {{ form.as_p }}
    Submit

    {% endif %}

New contributor

Aras Bulak is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật