sumanth
sumanth

Reputation: 781

Django/python: (1048, "Column 'date' cannot be null")

I have created a Django project in which type-1 users can create a Post and type-2 users can bid on a post out of post_queryset = Post.objects.filter(accepted=False). Finally, post_owner can accept a bid. After accepting I wanted to remove the accepted_object from post_queryset. So, I created a view(accept_bid) in which a type-1 user can accept a bid and simultaneously it passes a BooleanField(accepted) = True. With this, the post will no longer appear in the post_list page. But when I saving the accept_bid instance, it raising an IntegrityError: (1048, "Column 'date' cannot be null"). I'm not sure whether my approach in changing the BooleanField() = True in my view is correct. I would appreciate helping me solve this.

Here's My code:

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:

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")

Upvotes: 0

Views: 2329

Answers (1)

souldeux
souldeux

Reputation: 3755

The error trips when you try to save form1 rather than when saving the accept_bid instance:

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

form1 is a ModelForm based on your Post model. Since your Post model already has an accepted attribute, you don't have to manually define a field for it like you did here - including that field in the Meta definition for the form like you've done is enough.

You will need to do one of three things from there:

  1. Also include the date field in your ModelForm so that it can be set by the submitter,

  2. Set up your model to either automatically include a date on creation (auto_now_add=True), or to allow that field to be blank. Or,

  3. Use commit=False to interrupt the save and add a date to your object:

    accepted = form1.save(commit=False)
    accepted.date = ...
    accepted.save()
    

Also note that here:

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

You save accepted to your database, then update the object locally. The second line is only updating the object in memory, not the database. If you print accepted.accepted it will indeed show up as True, but if you re-fetch the object from the database and then try it again it'll show up as False since that change was never saved to the DB.

Upvotes: 2

Related Questions