django csv file validation in model form clean method

django csv file validation in model form clean method

Following is the FileModel to upload a csv file in my Django application:

Following is the FileModel to upload a csv file in my Django application:

class File(models.Model):
  uploaded_by = models.ForeignKey(
    User,
    on_delete=models.CASCADE,
  )
  csv_file = models.FileField(
    upload_to='csvfiles/',
  )

On invocation of the /upload_file url pattern, the upload_csv_file view executes as follows:

 def upload_csv_file(request):
   if request.method == 'POST':
      csv_form = CSVForm(request.POST, request.FILES)
      if csv_form.is_valid():
        file_uploaded = csv_form.save(commit=False)
        file_uploaded.uploaded_by = request.user
        csv_form.save()
        return HttpResponse("<h1>Your csv file was uploaded</h1>")

elif request.method == 'GET': csv_form = CSVForm() return render(request, './mysite/upload_file.html', {'csv_form': csv_form})

In forms.py I am validating the following:

  • file extension (.csv)
  • file size (5 mb)
class CSVForm(forms.ModelForm):

class Meta: model = File fields = ('csv_file',)

def clean_csv_file(self): uploaded_csv_file = self.cleaned_data['csv_file']

if uploaded_csv_file: filename = uploaded_csv_file.name if filename.endswith(settings.FILE_UPLOAD_TYPE): if uploaded_csv_file.size < int(settings.MAX_UPLOAD_SIZE): return True else: raise forms.ValidationError( "File size must not exceed 5 MB") else: raise forms.ValidationError("Please upload .csv extension files only")

return uploaded_csv_file

def clean(self): cleaned_data = super(CSVForm, self).clean() uploaded_csv_file = cleaned_data.get('csv_file') return uploaded_csv_file

However i encounter the following error on submitting the file upload button:

  Attribute error: 'bool' object has no attribute 'get'

I am unsure whether the 'def clean_csv_file(self)' is being invoked or not.

There are ways to validate file extension and size within the function-based view, but I would like to validate the file attributes in the ModelForm's clean() method itself.

Please suggest a solution to apply the same. Thanks!

django

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Python Django Tutorial | Django Course

🔥Intellipaat Django course: https://intellipaat.com/python-django-training/ 👉This Python Django tutorial will help you learn what is django web development &...

django-allauth Django REST Framework |teratail

Djangoアプリを、当初は Django REST Framework (DRF) を使わずに作成しました。(認証パッケージは、 django-allauthを使用)アプリリリース後に、DRFも追加で導入して、DRFで作成したAPIでのデ

Django REST Framework Course for Beginners

In this article we are going to talk about Django REST Framework Course for Beginners, also for more information you can check the complete video for th

Хранение изображений с помощью Django/Django REST

Проблема Мне в ходе разработки часто приходится работать с моделями, в которых должны быть изображения. Для удобной организации я использую древовидную структуру...

How to Integrate Django to any Javascript Front End // Django to React // Django to Angular

Learn the basic technique to Integrate Django to any Javascript Front End // Django to React // Django to Angular