Multiple file uploead. Getting error file upload Field 'id' expected a number but got <InMemoryUploadedFile: test image.jpg (image/jpeg)>

I have a model that has a manytomany to another model. Its a competition and the other model is sponsor images (sponsor_logo) for the competition. I'm creating a form to create a competition and all of the associated information. I keep getting this error when submitting the from and I can't figure out why. I am creating the sponsor object, assigning the appropriate fields, saving and linking to the competition model. But I get the type error on the ID. Shouldn't that pass between these objects?

class Competition(models.Model):
    name = models.CharField(max_length=255)
    registration_deadline = models.DateTimeField()
    allowed_divisions = models.ManyToManyField(Division, related_name='allowed_competitions')
    allowed_weight_classes = models.ManyToManyField(WeightClass, related_name='allowed_competitions')
    federation = models.ForeignKey(Federation, on_delete=models.SET_NULL, null=True, blank=True)  
    sponsor_logos = models.ManyToManyField('Sponsor', blank=True)


    def __str__(self):
        return self.name


class Sponsor(models.Model):
    name = models.CharField(max_length=255)
    logo = models.ImageField(upload_to='sponsor_logos/')

    def __str__(self):
        return self.name

views.py

class CompetitionCreateView(LoginRequiredMixin, generic.CreateView):
    model = Competition
    form_class = CompetitionForm
    template_name = 'competitions/competition_form.html'
    success_url = reverse_lazy('competitions:competition_list')

    def form_invalid(self, form):
        print("Form is invalid")
        print(form.errors)
        return super().form_invalid(form)

    def form_valid(self, form):
        form.instance.organizer = self.request.user
        competition = form.save(commit=False)

        try:
            if self.request.FILES.getlist('sponsor_logos'):
                competition.save()
                for logo in self.request.FILES.getlist('sponsor_logos'):
                    sponsor = Sponsor.objects.create(
                        name=logo.name  # Or any other suitable name
                    )
                    sponsor.logo.save(logo.name, logo, save=True)
                    competition.sponsor_logos.add(sponsor)
            else:
                competition.save()
        except Exception as e:
        return super().form_valid(form)class 

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/competitions/create/

Django Version: 5.1.3
Python Version: 3.12.3
Installed Applications:
['accounts',
 'django.contrib.auth',
 'django.contrib.admin',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django_browser_reload',
 'axes',
 'django_cotton',
 'django_bootstrap5',
 'competitions',
 'phonenumber_field',
 'tinymce',
 'crispy_forms',
 'crispy_bootstrap5',
 'django_filters',
 'channels',
 'chat',
 'widget_tweaks']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django_browser_reload.middleware.BrowserReloadMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'axes.middleware.AxesMiddleware',
 'whitenoise.middleware.WhiteNoiseMiddleware']



Traceback (most recent call last):
  File "/home/blake/PycharmProjects/ComPodium/.venv/lib/python3.12/site-packages/django/db/models/fields/__init__.py", line 2123, in get_prep_value
    return int(value)
           ^^^^^^^^^^

The above exception (int() argument must be a string, a bytes-like object or a real number, not 'TemporaryUploadedFile') was the direct cause of the following exception:
  File "/home/blake/PycharmProjects/ComPodium/.venv/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "/home/blake/PycharmProjects/ComPodium/.venv/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/blake/PycharmProjects/ComPodium/.venv/lib/python3.12/site-packages/django/views/generic/base.py", line 104, in view
    return self.dispatch(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/blake/PycharmProjects/ComPodium/.venv/lib/python3.12/site-packages/django/contrib/auth/mixins.py", line 73, in dispatch
    return super().dispatch(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/blake/PycharmProjects/ComPodium/.venv/lib/python3.12/site-packages/django/views/generic/base.py", line 143, in dispatch
    return handler(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/blake/PycharmProjects/ComPodium/.venv/lib/python3.12/site-packages/django/views/generic/edit.py", line 182, in post
    return super().post(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/blake/PycharmProjects/ComPodium/.venv/lib/python3.12/site-packages/django/views/generic/edit.py", line 151, in post
    return self.form_valid(form)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/home/blake/PycharmProjects/ComPodium/competitions/views.py", line 160, in form_valid
    return super().form_valid(form)
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/blake/PycharmProjects/ComPodium/.venv/lib/python3.12/site-packages/django/views/generic/edit.py", line 133, in form_valid
    self.object = form.save()
                  ^^^^^^^^^^^
  File "/home/blake/PycharmProjects/ComPodium/.venv/lib/python3.12/site-packages/django/forms/models.py", line 555, in save
    self._save_m2m()
    ^^^^^^^^^^^^^^^^
  File "/home/blake/PycharmProjects/ComPodium/.venv/lib/python3.12/site-packages/django/forms/models.py", line 536, in _save_m2m
    f.save_form_data(self.instance, cleaned_data[f.name])
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/blake/PycharmProjects/ComPodium/.venv/lib/python3.12/site-packages/django/db/models/fields/related.py", line 1969, in save_form_data
    getattr(instance, self.attname).set(data)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/blake/PycharmProjects/ComPodium/.venv/lib/python3.12/site-packages/django/db/models/fields/related_descriptors.py", line 1344, in set
    else self.target_field.get_prep_value(obj)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/blake/PycharmProjects/ComPodium/.venv/lib/python3.12/site-packages/django/db/models/fields/related.py", line 1148, in get_prep_value
    return self.target_field.get_prep_value(value)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/blake/PycharmProjects/ComPodium/.venv/lib/python3.12/site-packages/django/db/models/fields/__init__.py", line 2125, in get_prep_value
    raise e.__class__(
    ^^^^^^^^

Exception Type: TypeError at /competitions/create/
Exception Value: Field 'id' expected a number but got <TemporaryUploadedFile: Xfinity_logo_2017_blk_RGB_edited.jpg (image/jpeg)>.
Вернуться на верх