Django при сохранении поля ManyToManyField выдает ошибку: Поле 'id' ожидало число, но получило 'str'

Я пытаюсь использовать поле ManyToManyField для создания атрибута модели с набором опций (экземпляров модели m2m). Когда я пытаюсь сохранить модель в ModelForm, save_m2m() выдает ошибку, говоря, что поле 'id' ожидало число, а получило 'T'.

Вот мой код:

Модель:

class Listing(models.Model):
idtag = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField(max_length=200)
author = models.ForeignKey(User, on_delete=models.CASCADE)
published = models.DateTimeField("Date Published", default=timezone.now)
description = models.TextField()
price = models.PositiveBigIntegerField()
crypto = models.ManyToManyField(Choices)
location = models.CharField(max_length=100)
only_location = models.BooleanField(default=False)
tags = TaggableManager()

def __str__(self):
    return self.title

def get_absolute_url(self):
    return reverse('main:listingdetails', kwargs={'pk': self.pk})

Вид:

@login_required
def createview(request):
    if request.method == "POST":
        creationform = ListingForm(request.POST, author=request.user)
        if creationform.is_valid():
            creationform.save(commit=False)
            creationform.save_m2m()
            listing = creationform.instance
            messages.success(request, "New Listing Created")
            return redirect(reverse('main:listingdetails', kwargs={'pk': listing.idtag}))
        else:
            messages.error(request, 'Please correct the error below.')

    creationform = ListingForm
    return render(request,
                "main/createlisting.html",
                context={"creationform":creationform})

Форма:

class ListingForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
    self.author = kwargs.pop('author', None)
    super(ListingForm, self).__init__(*args, **kwargs)

cryptoList = (("ETH", "Ethereum"),
    ("TRP", "TroupeCoin"))

crypto = forms.ChoiceField(choices=cryptoList)

def save(self, commit=True):
        listing = super(ListingForm, self).save(commit=False)
        listing.author = self.author
        if commit:
            listing.save()

class Meta:
    model = Listing
    fields = ('title', 'description', 'price', 'crypto', 'tags')

Traceback:

The above exception (invalid literal for int() with base 10: 'T') was the direct cause of the following exception:

  File "C:\Users\-\AppData\Roaming\Python\Python39\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)

  File "C:\Users\-\AppData\Roaming\Python\Python39\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)

  File "C:\Users\-\AppData\Roaming\Python\Python39\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)

  File "C:\Users\-\Downloads\zephyrus\main\views.py", line 102, in createview
    creationform.save_m2m()

  File "C:\Users\-\AppData\Roaming\Python\Python39\site-packages\django\forms\models.py", line 451, in _save_m2m
    f.save_form_data(self.instance, cleaned_data[f.name])

  File "C:\Users\-\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields\related.py", line 1668, in save_form_data
    getattr(instance, self.attname).set(data)

  File "C:\Users\-\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields\related_descriptors.py", line 1007, in set
    else self.target_field.get_prep_value(obj)

  File "C:\Users\-\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields\related.py", line 977, in get_prep_value
    return self.target_field.get_prep_value(value)

  File "C:\Users\-\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields\__init__.py", line 1825, in get_prep_value
    raise e.__class__(


Exception Type: ValueError at /listing/create/

Exception Value: Field 'id' expected a number but got 'T'.

Спасибо за любую помощь.

Вернуться на верх