Django / python:(1048,“Column'date'不能为null”)

时间:2016-08-08 20:43:17

标签: django django-models django-forms django-views

我创建了一个Django项目,其中第1类用户可以创建帖子,而第2类用户可以在post_queryset = Post.objects.filter(accepted = False)之后对帖子出价。最后,post_owner可以接受出价。接受后我想从post_queryset中删除accepted_object。因此,我创建了一个视图(accept_bid),其中一个类型1用户可以接受出价,同时它传递一个BooleanField(接受)= True。这样,帖子将不再出现在post_list页面中。但是当我保存accept_bid实例时,它引发了IntegrityError:(1048,“Column'date'不能为null”)。我不确定我在视图中更改BooleanField()= True的方法是否正确。我很乐意帮助我解决这个问题。

这是我的代码:

Models.py:

class Post(models.Model):

    item = models.CharField(max_length=20)
    post_owner = models.OneToOneField(settings.AUTH_USER_MODEL, default=1)
    date = models.DateField()
    accepted = models.BooleanField(default = False)


class Bid(models.Model):

    post = models.ForeignKey(Post, related_name = bids)
    amount = models.IntegerField(max_length = 20)
    bidder = models.ForeingKey(settings.AUTH_USER_MODEL)

class Auction(models.Model):

    post = models.OneToOneField(Post)
    post_owner = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
    bid = models.OneToOneField('truck.Bid', related_name='auctions')

forms.py:

class AcceptedForm(forms.ModelForm):
accepted = forms.BooleanField(required=False)

    class Meta:
        model = Post
        fields = ('accepted', )

views.py:

def accept_bid(request, post_id, bid_id):

    post = get_object_or_404(Post, id=post_id)
    bid = get_object_or_404(Bid, id=bid_id)
    if request.method=='POST':
        form = AuctionForm(request.POST or None)
        form1 = AcceptedForm(request.POST)
        if form.is_valid() and form1.is_valid():
            accept_bid = form.save(commit=False)
            accept_bid.bid = bid
            accept_bid.post = post
            accept_bid.post_owner = request.user
            accepted = form1.save()
            accepted.accepted = True
            accept_bid.save()

            form.save()
            form1.save()
    else:
        form = AuctionForm()
        form1 = AcceptedForm()

    context = {

            "bid_id" : bid_id,
            "post_id" : post_id,
            "bid": bid,
            "post":post,
            'form': form
            'form1': form1,

         }
     return render(request, 'loggedin_load/active_deals.html', context)

回溯:

Traceback:

File "c:\python34\lib\site-packages\django\db\backends\mysql\base.py" in execute
  112.             return self.cursor.execute(query, args)

File "c:\python34\lib\site-packages\MySQLdb\cursors.py" in execute
  226.             self.errorhandler(self, exc, value)

File "c:\python34\lib\site-packages\MySQLdb\connections.py" in defaulterrorhandler
  36.         raise errorvalue

File "c:\python34\lib\site-packages\MySQLdb\cursors.py" in execute
  217.             res = self._query(query)

File "c:\python34\lib\site-packages\MySQLdb\cursors.py" in _query
  378.         rowcount = self._do_query(q)

File "c:\python34\lib\site-packages\MySQLdb\cursors.py" in _do_query
  341.         db.query(q)

 File "c:\python34\lib\site-packages\MySQLdb\connections.py" in query
   280.             _mysql.connection.query(self, query)

 During handling of the above exception ((1048, "Column 'date' cannot be null")), another exception occurred:

File "c:\python34\lib\site-packages\django\core\handlers\base.py" in  get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "c:\python34\lib\site-packages\django\core\handlers\base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "c:\python34\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "c:\python34\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "C:\Users\sumanth\Desktop\django-custom-user-master\search field\Project\mysite\personal\views.py" in accept_bid
  447.          accepted = form1.save()

File "c:\python34\lib\site-packages\django\forms\models.py" in save
  451.             self.instance.save()

File "c:\python34\lib\site-packages\django\db\models\base.py" in save
  708.                        force_update=force_update, update_fields=update_fields)

File "c:\python34\lib\site-packages\django\db\models\base.py" in save_base
  736.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File "c:\python34\lib\site-packages\django\db\models\base.py" in _save_table
  820.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "c:\python34\lib\site-packages\django\db\models\base.py" in _do_insert
  859.                                using=using, raw=raw)

File "c:\python34\lib\site-packages\django\db\models\manager.py" in manager_method
  122.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "c:\python34\lib\site-packages\django\db\models\query.py" in _insert
  1039.         return query.get_compiler(using=using).execute_sql(return_id)

File "c:\python34\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  1060.                 cursor.execute(sql, params)

File "c:\python34\lib\site-packages\django\db\backends\utils.py" in execute
  79.             return super(CursorDebugWrapper, self).execute(sql, params)

File "c:\python34\lib\site-packages\django\db\backends\utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

File "c:\python34\lib\site-packages\django\db\backends\mysql\base.py" in execute
 117.                 six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])

File "c:\python34\lib\site-packages\django\utils\six.py" in reraise
  685.             raise value.with_traceback(tb)

File "c:\python34\lib\site-packages\django\db\backends\mysql\base.py" in execute
  112.             return self.cursor.execute(query, args)

File "c:\python34\lib\site-packages\MySQLdb\cursors.py" in execute
  226.             self.errorhandler(self, exc, value)

File "c:\python34\lib\site-packages\MySQLdb\connections.py" in defaulterrorhandler
  36.         raise errorvalue

File "c:\python34\lib\site-packages\MySQLdb\cursors.py" in execute
  217.             res = self._query(query)

File "c:\python34\lib\site-packages\MySQLdb\cursors.py" in _query
  378.         rowcount = self._do_query(q)

File "c:\python34\lib\site-packages\MySQLdb\cursors.py" in _do_query
  341.         db.query(q)

File "c:\python34\lib\site-packages\MySQLdb\connections.py" in query
  280.             _mysql.connection.query(self, query)

Exception Type: IntegrityError at /post/3/bid/7/
Exception Value: (1048, "Column 'date' cannot be null")

1 个答案:

答案 0 :(得分:2)

当您尝试保存form1而不是保存accept_bid实例时,错误会跳闸:

File "C:\Users\sumanth\Desktop\django-custom-user-master\search field\Project\mysite\personal\views.py" in accept_bid
  447.          accepted = form1.save()

form1是基于您的Post模型的ModelForm。由于您的Post模型已经具有accepted属性,因此您不必像在此处那样为其手动定义字段 - 包括表单的Meta定义中的该字段你做的就够了。

你需要从那里做三件事之一:

  1. 还在ModelForm中包含date字段,以便提交者可以设置该字段,

  2. 将模型设置为自动包含创建日期(auto_now_add=True),或允许该字段为空。或者,

  3. 使用commit=False中断保存并为对象添加日期:

    accepted = form1.save(commit=False)
    accepted.date = ...
    accepted.save()
    
  4. 另请注意:

    accepted = form1.save()
    accepted.accepted = True
    

    accepted保存到数据库,然后在本地更新对象。第二行只更新内存中的对象,而不是数据库。如果你print accepted.accepted它确实会显示为True,但是如果你从数据库中重新获取该对象然后再次尝试它将显示为False,因为该更改是从未保存到数据库。