我有一个模型,我试图在用户提交表单时将用户保存到模型数据库。我有一个网站可以做到这一点,但现在我的编辑说"在旧式班上使用超级"
我正在使用django 1.8而且我得到了
/ auction / createview / NOT NULL约束中的IntegrityError失败: auction_auction.user_id
这是我能得到的最好的错误。我做过的所有修修补补
class AuctionCreateView(LoginRequiredMixin,CreateView):
model = Auction
action = "created"
form_class = AuctionForm
auction_form = AuctionForm(initial={'user':request.user})
class AuctionForm(forms.ModelForm):
class Meta:
model = Auction
fields = (
"user",
"item_name",
"reserve",
"start_date",
"end_date",
"description",
"tags",
)
class Auction(models.Model):
user = models.ForeignKey(User)
item_id = models.CharField(max_length=255, blank=True, null=True)
item_name = models.CharField(max_length=255, blank=True, null=True)
winner = models.ForeignKey(User, related_name='Auction_Winner', blank=True, null=True)
reserve = MoneyField(max_digits=10, decimal_places=2, default_currency='USD')
created = models.DateTimeField(editable=False, null=True)
slug = AutoSlugField(('slug'), max_length=128, unique=True, populate_from=('item_name',))
start_date = models.DateTimeField(verbose_name="Start date")
end_date = models.DateTimeField(verbose_name="End date")
active = models.BooleanField(default=False, verbose_name='Active')
total_bids = models.IntegerField(default=0, verbose_name='Total bids')
date_added = models.DateTimeField(auto_now_add=True, verbose_name='Date added')
last_modified = models.DateTimeField(auto_now=True, verbose_name='Last modified')
description = models.TextField(max_length=3000)
tags = tagging.fields.TagField()
# bid_set = models.IntegerField(default= 0, verbose_name = "Bid set")
starting_amount = MoneyField(max_digits=10, decimal_places=2, default_currency='USD')
def __unicode__(self):
return '%s selling %s' % (self.user, self.item_name)
def _get_increment(self):
""" add some logic to base incrementing amount on starting price """
def get_absolute_url(self):
return reverse('auction_detail',
kwargs={'slug': self.slug})
当我看到this post时,我以为我能够弄明白。谢谢★✩
答案 0 :(得分:0)
You need insert user_id before form save.
AuctionForm - need update request.user value. Added this fields from form initial.
答案 1 :(得分:0)
您必须在Auction表单类的字段中包含'user'才能解决该错误,并将一个初始参数放在views.py中的表单实例上,如
auction_form = AuctionForm(initial={'user':request.user})
因为form_valid方法上的request.user无法正常工作