0

I am trying to make an app for parking. What I need is to save multiple instances of the same object in the DB. Basically, if the user selects that he wants to park from 2018-09-23 (parking_on) till 2018-09-28 (parking_off), what I need is to save the same model 5 times with all the required details. enter image description here

These are my models:

from django.db import models
from django.urls import reverse
from django.db.models.signals import pre_save
from django.utils.text import slugify
from django.conf import settings
from django.utils import timezone
# from datetime import datetime
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from datetime import datetime, timedelta, time
today = datetime.now().date()
tomorrow = today + timedelta(1)
now = datetime.now()
l = now.hour
m=int(now.strftime("%H"))

class ParcareManager(models.Manager):

    def active(self, *args, **kwargs):
        return super(ParcareManager, self).filter(draft=False).filter(parking_on__lte=timezone.now())


class Parcare(models.Model):
    PARKING_PLOT = (
        ('P1', 'Parking #1'), ('P2', 'Parking #2'),('P3', 'Parking #3'))
    user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, 
                            null=True, default=1, on_delete=True)
    email=models.EmailField(blank=True, null=True)
    parking_on = models.DateField(auto_now=False, auto_now_add=False,
                                  blank=True, null=True,
                                  help_text='Alege data cand doresti sa vii in office')
    parking_off = models.DateField(
        auto_now=False, auto_now_add=False, blank=True, null=True, help_text='Alege Data Plecarii')  
    numar_masina = models.CharField(max_length=8, default="IF77WXV", 
    blank=True, null=True, help_text='Introdu Numarul Masinii')
    location = models.CharField(max_length=3, blank=True, default="P1",
                                null=True, choices=PARKING_PLOT,
                                help_text='Alege Locul de Parcare Dorit')
    updated = models.DateTimeField(auto_now=True, auto_now_add=False,blank=True, null=True)
    timestamp=models.DateTimeField(auto_now=False, auto_now_add=True,blank=True, null=True)
    venire = models.TimeField(default=time(9, 00), auto_now=False,
     auto_now_add=False, help_text='Alege Ora Venirii')
    plecare = models.TimeField(default=time(
        18, 00), auto_now=False, auto_now_add=False, help_text='Alege Ora Plecarii')
    booked = models.BooleanField(default=1)
    objects = ParcareManager()

    def __str__(self):
        return self.location + " | " + str(self.parking_on) + " | " + str(self.parking_off)

    class Meta:
        verbose_name_plural = "parcare"
        ordering = ["-parking_on"]

    def clean(self):        
        q = Parcare.objects.filter(parking_on=self.parking_on)

        if self.location in q: #nu merge sa filtram si sa vedem daca locul a fost luat deja
            raise ValidationError(_('Sorry this plot is already taken!'))

        if self.parking_on == today:  # merge--vedem dak parcam azi si dak e tecut de ora 16
            raise ValidationError({'parking_on': _('Please book for a date starting tomorrow')})

        if self.parking_off < self.parking_on: #merge-vedem daca bookam in trecut
            raise ValidationError({'parking_off': _('You cant book for a past date!')})
        if m < 17: # se schimba semnul in > cand va fi in productie
            raise ValidationError({'parking_on':_('Sorry the booking session is closed!')})

        if self.parking_on != self.parking_off:
            delta= self.parking_off.day-self.parking_on.day
            print(delta)
            for i in range(delta):                
                self.user=self.user
                self.email=self.email
                self.parking_on=self.parking_on+timedelta(i)
                self.parking_off=self.parking_off
                self.numar_masina=self.numar_masina
                self.location=self.location
                self.venire="00:00:00"
                self.plecare = "00:00:00"
                self.booked=self.booked
                self.save

If someone could help me, I would owe you a lot!

3
  • do you use admin panel to enter the details? or are you developing your own interface ? Commented Sep 22, 2018 at 20:53
  • am doing them in admin, there is more easier to implement! thank you for your time! Commented Sep 22, 2018 at 21:29
  • Instead of trying "save an object for each day", you would do better to set your code to handle "in" and "out" times and configure off that. Commented Sep 22, 2018 at 22:57

1 Answer 1

2

Inside the model Parcare, define a function save() as follows:

    def save(self):
        list=[]
        d=self.parking_on
        while d<self.parking_off:
            list.append(
                Parcare(user=self.user,
                    email=self.email,
                    #remaing fields in the model
                    parking_on=d,
                    parking_off=d,
                    #remaing fields in the model    
                    )
                )
            d= d +timedelta(days=1)

        Parcare.objects.bulk_create(list)

You need to import the following in order to run the above code(you have imported it in your code):

from datetime import timedelta
Sign up to request clarification or add additional context in comments.

9 Comments

is there a way to put some kind of control, e.g. if the location is booked on 5th day to raise an erorr message ("The location during this day is booked!) and not to book that day. Thank you very much @Abhijith K!
I dont understant it clearly.. What I understood is that on a particalar day if a location is booked, then booking on that day on that location is not allowed. Am I right?
Yes, lets supose you book all the time on location P1. And when you save from 24th till 27th you should receive a message that on P1 already one booked his car there. Did u get it? Thank you!
I think you can add a unique_together constrain to the date and location so that multiple entries with same date and location cannot be entered into the DB. The django admin panel will show the msg stating that this record is already in the db.
man you are a djang0 rock star! that did the trick! if i want it to check also the leaving and coming hour? i saw that django doesn't allow 4 different fields in the unique_together = ("parking_on", "location", "venire", "plecare"). Just to elaborate myself, if the plot is free on 25.10.2018 from 19h till 24, i would like to give the permission to park there only during that time gap and also during that day. is this too much? thank you for all your valuable time!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.