Django保存ManyToManyField时出错:字段“id”应为数字,但得到“str”

2024-06-16 13:54:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用ManyToManyField创建一个带有一组选项的模型属性(m2m模型的实例)。当我在ModelForm中保存模型时,save_m2m()会给出一个错误,指出字段“id”需要一个数字,但得到了“U”

这是我的密码:

型号:

class Choices(models.Model):
description = models.CharField(max_length=100)


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()
currency = 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)

currencyList = (("USD", "US Dollars"),
    ("GBP", "Pounds"))

currency = forms.ChoiceField(choices=currencyList)

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', 'currency', 'tags')

回溯:

The above exception (invalid literal for int() with base 10: 'U') 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 'U'.

谢谢你的帮助


Tags: inpyselfmodelsrequestsavepackagesline