0

Bit of a random question but ill try my best to describe what im trying to do. I am building a app to manage a set of physical assets which get loaned out.

To return an asset the user visits /return/1/ which clears the name of the user, date borrowed, date returned etc

view.py

 def returnlaptop(request, laptop_pk):
        Laptops.objects.filter(pk=laptop_pk).update(laptop_status='In')
        Laptops.objects.filter(pk=laptop_pk).update(user='')
        Laptops.objects.filter(pk=laptop_pk).update(borrowed_date='')
        Laptops.objects.filter(pk=laptop_pk).update(return_date='')
        return HttpResponseRedirect('/')

This works well except for when i try and update the values in the models.datefield

[u"' ' value has an invalid date format. It must be in YYYY-MM-DD format."]

Is there anyway around this? or am I going about this the completely wrong way?

Cheers Xcom

xc0m
  • 121
  • 5

1 Answers1

0

I'm not 100% sure but I think that hits the database 4 times...

The first issue is that update is meant for use on a queryset. You are filtering on the primary key so you are only getting 1 object back. Which means that you should use get instead like this

laptop = Laptops.objects.get(pk=laptop_pk)

and now you can use that to properly fetch the object from the database, modify it, and save it like so

laptop = Laptops.objects.get(pk=laptop_pk)
laptop.laptop_status = 'In'
laptop.user = ''
...
laptop.save()

which would only hit the database 1 time.

The final issue is that you are attempting to set a date to an empty string. That won't work because it is expecting a date object. One thing you can do is modify your model so that the dates can be blank and so that the database accepts null values.

class Laptops(models.Model):
    ...
    borrowed_date = models.DateField(null=True, blank=True)
    return_date = models.DateField(null=True, blank=True)

The other thing you can do is use the minimum date can be accessed with timezone.datetime.min

Ngenator
  • 10,909
  • 4
  • 41
  • 46
  • Thanks Ngenator, I made the following changes to no avail :( [u"'' value has an invalid date format. It must be in YYYY-MM-DD format."] – xc0m Apr 03 '13 at 23:35
  • @xc0m You can't set it to an empty string, try `None` or `timezone.datetime.min` – Ngenator Apr 03 '13 at 23:41