Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

(Django - Python) Problems with timedelta saving form

I have a problem with my auction site because when I publish an auction the function doesn't save my variable correctly, these are my codes:

  • views.py

    import datetime
    from datetime import timedelta
    
    def publishAuction(request):
    
      user=request.user
    
      form = auctionForm(request.POST, request.FILES)
    
      if request.method=="POST":
    
          if form.is_valid():
    
              auction=form.save(commit=False)
              auction.advertiser=user
              auction.startDate=datetime.datetime.now()
              auction.endDate=auction.startDate+timedelta(days=1)
              auction.endPrice=request.POST.get("startPrice")
              auction.save()
              return redirect("../")
    
          else:
    
              form=auctionForm() 
    
  • models.py

    class Auction(models.Model):
    
      advertiser = models.ForeignKey(User, on_delete=models.CASCADE, related_name='auction_advertiser', null=True)
      winner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='auction_winner', null=True)
      title = models.CharField(max_length=30)
      text = models.TextField()
      startPrice = models.FloatField(null=True)
      endPrice = models.FloatField()
      status = models.BooleanField(default=True)
      image = models.ImageField(upload_to='images/')
      startDate = models.DateTimeField(auto_now=False, auto_now_add=True)
      endDate = models.DateTimeField(auto_now=False, auto_now_add=True)
    

The publication is done correctly, everything except endDate that is always equal to startDate...

I have tried also with datetime.datetime.now instead of auction.startDate or datetime.timedelta(days=1) but when I get the value in the shell is always the same...

In the scratch.py file I write the same codes and it works, I don't know why doesn't work in the function... :S

Thanks to everyone!

question from:https://stackoverflow.com/questions/65833653/django-python-problems-with-timedelta-saving-form

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have defined auto_now_add=True on your endDate field, which renders field uneditable and set as now(). From documentation:

Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...