Django 为什么我被禁止直接分配到多对多集合的前端。?
当我试图在拍卖观察模型上添加数据时,我遇到了这个错误。我试着与观看拍卖和产品表建立许多关系。但是为什么我会犯这个错误。请帮帮我Django 为什么我被禁止直接分配到多对多集合的前端。?,django,django-models,django-rest-framework,django-views,django-database,Django,Django Models,Django Rest Framework,Django Views,Django Database,当我试图在拍卖观察模型上添加数据时,我遇到了这个错误。我试着与观看拍卖和产品表建立许多关系。但是为什么我会犯这个错误。请帮帮我 models.py from django.db import models from PIL import Image from datetime import datetime, timedelta from django.contrib.auth.models import User # Create your models here. class Product
models.py
from django.db import models
from PIL import Image
from datetime import datetime, timedelta
from django.contrib.auth.models import User
# Create your models here.
class Products(models.Model):
product_img = models.ImageField(upload_to='pics')
product_title = models.CharField(max_length=100)
price = models.IntegerField()
deadline = models.DateTimeField()
def save(self, *args, **kwargs):
super(Products, self).save(*args, **kwargs)
img=Image.open(self.product_img.path)
if img.height >= 300 and img.width >=300:
img = img.resize((200, 300)) # resize use to resize image, don't care about ration
# output_size = (200,300)
# img.thumbnail(output_size) # thumbnail use to resize image with aspect ration
img.save(self.product_img.path)
class Auction_Watching(models.Model):
product_info = models.ManyToManyField(Products, null=True )
User_id = models.IntegerField()
current_bid = models.IntegerField(null=True)
action_status = models.BooleanField(default='True')
def __str__(self):
return self.name
视图.py
在做了一些研究之后,我得到了自己问题的答案。 在django中,我们不能在许多字段中直接赋值,例如:
product\u watch=Auction\u Watching.objects.create(product\u info=product\u information,User\u id=User\u id)
这里的项目信息在许多字段中,我直接插入了django不允许的值。相反,我们需要做的是:首先,我们需要在变量中获取该表的所有值,如:product\u description=Products.objects.get(id=pk)
然后在表中创建不包含此多个字段的值,如:product\u watch=Auction\u Watching.objects.create(User\u id=User\u id)
。然后在下一行添加许多字段,如:product\u watch.product\u info.add(product\u description)
,您不需要使用save()
def auction_watch(request,pk):
username=request.session['username']
user_id= request.session['value']
product_information = Products.objects.get(id=pk)
product_watch = Auction_Watching.objects.create(product_info=product_information, User_id=user_id)
return render(request, 'auctionApp/auction_watch.html')