def validate(self, data): """ Check that start is before finish. """ room = Room() room_value = room.get_value_by_id( data.get('room'), nested_id=data.get('hotel', {}).get("public_id") ) if not room_value: raise serializers.ValidationError( { 'room': "room don't not exists" } ) filter_rate = Rate.objects.filter( inventory__date=data.get('date'), room__public_id=data.get('room') ) if filter_rate.exists(): raise serializers.ValidationError( { 'date': ( 'It already exists in the inventory in the room ' 'on this date' ) } ) data['room'] = room_value return data
def get_queryset(self): """ Get the list of items for this view. This must be an iterable, and may be a queryset. Defaults to using `self.queryset`. This method should always be used rather than accessing `self.queryset` directly, as `self.queryset` gets evaluated only once, and those results are cached for all subsequent requests. You may want to override this if you need to provide different querysets depending on the incoming request. (Eg. return a list of items that is specific to the user) """ # NOQA assert self.queryset is not None, ( "'%s' should either include a `queryset` attribute, " "or override the `get_queryset()` method." % self.__class__.__name__ ) hotel_id = self.kwargs.get('public_id') self.valid_hotel(hotel_id) rooms = Room() values = rooms.get_many_values( self.kwargs.get('public_id') ) return values
def get_queryset(self) -> QueryType[User]: room_title = self.kwargs['room_title'] room = get_object_or_404(Room, room_title=room_title) room_users = room.users.annotate( texts_count=Count('texts', filter=Q(texts__room=room))) Room.calculate_current_turn_user(room_title, self.request.user) # recalculate return room_users.all().order_by('membership__id')
def resetRoomCount(): try: room = Room.objects.get(pk=1) room.count = 0 room.save() except Room.DoesNotExist: room = Room(id=1, name="sample room", count=1) room.save()
def create_room(number, capacity=0, commit=True, **override): defaults = {'name': str(number), 'beds_single': capacity, 'available_beds_single': capacity} defaults.update(**override) room = Room(**defaults) if commit: room.save() return room
def _create_room(self, room): r = Room(code=room['code'], name=room['name'], floor=1, type=room['type'], access=room['access'], reservable=True) r.save() return r
def test_filter(self): Room.create(325, 100, False) Room.create(314, 20, True) response = self.client.get(self.FILTER_PATH, data={'is_computer_room': 'true'}) self.assertEqual(response.status_code, status.HTTP_200_OK) response_data = response.json() for dict_ in response_data: self.assertTrue(dict_['is_computer_room'])
def test_filter_min_capacity(self): Room.create(326, 100, False) Room.create(315, 20, True) response = self.client.get(self.FILTER_PATH, data={'min_capacity': 50}) self.assertEqual(response.status_code, status.HTTP_200_OK) response_data = response.json() for dict_ in response_data: self.assertGreaterEqual(dict_['capacity'], 50)
def setUp(self): self.su = User.objects.create_user(username="******", password="******") self.su.is_staff, self.su.is_superuser = True, True self.su.first_name = "Super" self.su.last_name = "User" self.su.save() self.r = Room(title="2E") self.r.save() self.client.login(username="******", password="******")
def test_no_duplicate(self): r = Room(title="1A") r.save() url = reverse("rooms:add") response = self.client.post(url, { "title": r.title, "unofficial_name": "", "description": "", "occupancy": 1, }) self.assertEqual(response.status_code, 200) self.assertContains( response, "A room with this title already exists.", )
def test_no_duplicate(self): r = Room(title="1A") r.save() url = reverse("rooms:add") response = self.client.post( url, { "title": r.title, "unofficial_name": "", "description": "", "occupancy": 1, }) self.assertEqual(response.status_code, 200) self.assertContains( response, "A room with this title already exists.", )
def handle_uploaded_file(csvfile): rooms = [] for row in csv.reader(csvfile, delimiter=','): name, desc, cap, hidden = row if name != "Name": rooms.append( Room(name=name, description=desc, capacity=cap, hidden=hidden)) Room.objects.bulk_create(rooms)
def post(self, request): name = request.POST.get('name') capacity = request.POST.get('capacity') projector = request.POST.get('projector') try: capacity = int(capacity) except: messages.info(request, f'Check capacity') return redirect(reverse('room_add')) if name and len(name) > 0: tmp_name = Room.objects.filter(name=name) if not tmp_name and capacity > 0: room = Room() room.name = name room.capacity = capacity room.projector = projector == 'on' room.save() return redirect(reverse('rooms')) else: messages.info(request, f'Check room name and capacity') return redirect(reverse('room_add')) else: messages.info(request, f'Check room name') return redirect(reverse('room_add'))
def get_object(self): """ Returns the object the view is displaying. You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf. """ hotel_id = self.kwargs.get('public_id') self.valid_hotel(hotel_id) room = Room() room_value = room.get_value_by_id( self.kwargs.get('room_id'), nested_id=hotel_id ) if not room_value: self.base_value_not_found('room') return room_value
def house_add_room(request, pk): house = House.objects.filter(pk=pk).get() if house.user != request.user: raise Http404 if request.method == 'POST': room = Room() room.user = request.user room.house = house if 'name' not in request.POST: return render( request, 'houses/room_add.html', { 'house': house, 'error': 'Please make sure to fill in all required details' }) else: room.name = request.POST['name'] if 'price' not in request.POST: return render( request, 'houses/room_add.html', { 'house': house, 'error': 'Please make sure to fill in all required details' }) else: room.price = request.POST['price'] if 'description' not in request.POST: return render( request, 'houses/room_add.html', { 'house': house, 'error': 'Please make sure to fill in all required details' }) else: room.description = request.POST['description'] room.save() try: for file in request.FILES.getlist('images'): image = RoomImage() image.room = room image.user = request.user image.image = file image.save() except Exception: pass return redirect('room_detail', pk=room.id) return render(request, 'houses/room_add.html', {'house': house})
def handle(self, *args, **options): for file in args: f = open(file, "r") for line in f: l = line.split() room = Room() room.number = l[0] room.capacity = int(l[1]) room.description = " ".join(l[2:]) room.short_unlock_time = datetime.now() room.save() self.stdout.write('Successfully imported\n')
def uploadphoto(request): if request.method == "POST": uploaded_image = request.FILES['image'] fssobj = FileSystemStorage() filename = fssobj.save(uploaded_image.name, uploaded_image) uploaded_image_url = fssobj.url(filename) room = Room(file=uploaded_image_url, Room_owner=request.POST['owner_name'], Room_location=request.POST['location'], Room_phnumber=request.POST['phone_number'], Room_price=request.POST['price'], pub_date=request.POST['pub_date'], Room_desc=request.POST['desc']) room.save() return HttpResponse( 'You have successfully uploaded the room photo with its detail<br><br><a href="/">Go to homepage</a>' ) else: return render(request, 'upload.html')
def perform_create(self, serializer: TextsFullSerializer): room = self.room if room.is_finished: raise PermissionDenied(detail='Story is finished') request_user = self.request.user request_membership = get_user_room_membership(request_user, room) if request_membership.status == Membership.STOPPED: raise PermissionDenied(detail='User has finished') current_turn_user: User = Room.calculate_current_turn_user(self.room_title, request_user) request_membership.refresh_from_db() if request_membership.status != Membership.CAN_WRITE: raise PermissionDenied(detail=self._wrong_turn_error_detail(current_turn_user)) serializer.save(author=request_user, room=room) room.save() # to update the modification timestamp _ = Room.calculate_current_turn_user(self.room_title, self.request.user) # recalculate send_channel_message(self.room_title, { 'type': WEBSOCKET_MSG_ADD_TEXT, 'room_title': self.room_title, 'username': request_user.username, })
def handle(self, *args, **options): for file in args: f = open(file, "r") for line in f: l = line.split() room = Room() room.number = l[0] room.capacity = int(l[1]) room.description = " ".join(l[2:]) room.short_unlock_time = timezone.now() room.save() self.stdout.write("Successfully imported\n")
def post(self): data = request.json parser.parse_args(strict=True) for room in json_data: if room.get("number") == data["number"]: return "Room exist" else: rooms_data.append( Room( data["number"], data["level"], data["status"], data["price"], ).to_dict()) write_data(rooms_data, json_file) return "Room added"
def get_queryset(self) -> QueryType[Text]: """Returns a queryset with a single record: the last, most recent text.""" room = self.room if room.is_finished: raise PermissionDenied(detail='Story is finished') is_new_user: bool = self.request.user not in room.users.all() queryset_with_last_text = Text.objects.filter(room=room).reverse()[:1] if is_new_user: # new users & guests can view anything return queryset_with_last_text user_membership = get_user_room_membership(self.request.user, room) if user_membership.status == Membership.STOPPED: raise PermissionDenied(detail='Left room') current_turn_user = Room.calculate_current_turn_user(self.room_title, self.request.user) user_membership.refresh_from_db() if user_membership.status != Membership.CAN_WRITE: raise PermissionDenied(detail=self._wrong_turn_error_detail(current_turn_user)) return queryset_with_last_text
def handle_uploaded_file(csvfile): rooms = [] for line, row in enumerate(csv.reader(csvfile, delimiter=','), start=1): try: name, desc, hidden, av_single, av_double, b_single, b_double = row except ValueError as e: raise ValidationError("Line %(line)s - %(error)s", code="invalid", params={"line": line, "error": e}) if name != "Name": rooms.append( Room(name=name, description=desc, hidden=hidden, available_beds_single=av_single, available_beds_double=av_double, beds_single=b_single, beds_double=b_double)) try: Room.objects.bulk_create(rooms) except ValueError: raise ValidationError( "Could not add rooms, check whether the file is properly formed and all values are correct.", code="invalid")
class TestEditRoom(TestCase): def setUp(self): self.su = User.objects.create_user(username="******", password="******") self.su.is_staff, self.su.is_superuser = True, True self.su.first_name = "Super" self.su.last_name = "User" self.su.save() self.r = Room(title="2E") self.r.save() self.client.login(username="******", password="******") def test_edit_room(self): url = reverse("rooms:edit", kwargs={"room_title": self.r.title}) response = self.client.post(url, { "room-title": self.r.title, "room-unofficial_name": "Starry Night Surprise", "room-description": "Previous home to the best person on earth.", "room-occupancy": 5, "residents-TOTAL_FORMS": 0, "residents-INITIAL_FORMS": 0, "residents-MAX_NUM_FORMS": 50, }, follow=True) url = reverse("rooms:view", kwargs={"room_title": self.r.title}) self.assertRedirects(response, url) self.assertContains(response, "2E") self.assertContains(response, "<dd>{0}</dd>".format(5), html=True) self.assertContains(response, "Starry Night Surprise") self.assertContains( response, "Previous home to the best person on earth.", ) self.assertNotContains(response, self.su.get_full_name()) def test_no_duplicate(self): r = Room.objects.create(title="1A") url = reverse("rooms:edit", kwargs={"room_title": self.r.title}) response = self.client.post( url, { "room-title": r.title, "room-unofficial_name": "", "room-description": "", "room-occupancy": 1, "residents-TOTAL_FORMS": 0, "residents-INITIAL_FORMS": 0, "residents-MAX_NUM_FORMS": 50, }) self.assertEqual(response.status_code, 200) self.assertContains( response, "A room with this title already exists.", ) def test_edit_room_minimal(self): url = reverse("rooms:edit", kwargs={"room_title": self.r.title}) response = self.client.post(url, { "room-title": self.r.title, "room-unofficial_name": "", "room-description": "", "room-occupancy": 5, "residents-TOTAL_FORMS": 0, "residents-INITIAL_FORMS": 0, "residents-MAX_NUM_FORMS": 50, }, follow=True) url = reverse("rooms:view", kwargs={"room_title": self.r.title}) self.assertRedirects(response, url) self.assertContains(response, "<dd>{0}</dd>".format(5), html=True) self.assertNotContains(response, "Starry Night Surprise") self.assertNotContains(response, self.su.get_full_name()) def test_bad_occupancy(self): url = reverse("rooms:edit", kwargs={"room_title": self.r.title}) response = self.client.post( url, { "room-title": self.r.title, "room-unofficial_name": "Starry Night", "room-description": "Home to the best person on earth.", "room-occupancy": -1, "residents-TOTAL_FORMS": 0, "residents-INITIAL_FORMS": 0, "residents-MAX_NUM_FORMS": 50, }) self.assertEqual(response.status_code, 200) self.assertContains( response, "Ensure this value is greater than or equal to 0.", ) response = self.client.post( url, { "title": self.r.title, "unofficial_name": "Starry Night", "description": "Home to the best person on earth.", "occupancy": "", "residents-TOTAL_FORMS": 0, "residents-INITIAL_FORMS": 0, "residents-MAX_NUM_FORMS": 50, }) self.assertEqual(response.status_code, 200) self.assertContains(response, "This field is required.") def test_bad_title(self): url = reverse("rooms:edit", kwargs={"room_title": self.r.title}) response = self.client.post( url, { "room-title": "", "room-unofficial_name": "", "room-description": "", "room-occupancy": 1, "residents-TOTAL_FORMS": 0, "residents-INITIAL_FORMS": 0, "residents-MAX_NUM_FORMS": 50, }) self.assertEqual(response.status_code, 200) self.assertContains(response, "This field is required.") response = self.client.post( url, { "room-title": "2a.", "room-unofficial_name": "", "room-description": "", "room-occupancy": 1, "residents-TOTAL_FORMS": 0, "residents-INITIAL_FORMS": 0, "residents-MAX_NUM_FORMS": 50, }) self.assertEqual(response.status_code, 200) self.assertContains( response, "Only alphanumeric characters are allowed.", ) response = self.client.post( url, { "room-title": "3_", "room-unofficial_name": "", "room-description": "", "room-occupancy": 1, "residents-TOTAL_FORMS": 0, "residents-INITIAL_FORMS": 0, "residents-MAX_NUM_FORMS": 50, }) self.assertEqual(response.status_code, 200) self.assertContains( response, "Only alphanumeric characters are allowed.", )
def store(request): if request.method == 'POST': r = Room() r.name = request.POST['name'] r.save() return redirect('/rooms')
def add_room(request): if (request.method == 'POST'): # print request.POST r = Room() r.name = request.POST['Name'] r.capacity = request.POST['capacity'] temp = request.POST.get('hasAC') if (temp != None): r.hasAC = True else: r.hasAC = False temp = request.POST.get('hasMic') if (temp != None): r.hasMic = True else: r.hasMic = False temp = request.POST.get('hasProjector') if (temp != None): r.hasProjector = True else: r.hasProjector = False r.save() return redirect('/') return render(request, 'add_room.html', {'user': request.user})
def add_room(request): form = RoomImageForm() if request.method == "POST": form = RoomImageForm(request.POST) room = Room() room.name = request.POST.get('name') room.description = request.POST.get('description') room.square = request.POST.get('square') room.price_per_m2 = request.POST.get('price_per_m2') room.price = request.POST.get('price') room.comments = request.POST.get('comments') room.status = get_object_or_404(Status, pk=2) room.save() roomImage = RoomImage() roomImage.room = get_object_or_404(Room, pk=room.pk) roomImage.image = request.POST.get('image') roomImage.save() return redirect('/') return render(request, 'add_room.html', { "form": form, "username": auth.get_user(request).username })
class TestEditRoom(TestCase): def setUp(self): self.su = User.objects.create_user(username="******", password="******") self.su.is_staff, self.su.is_superuser = True, True self.su.first_name = "Super" self.su.last_name = "User" self.su.save() self.r = Room(title="2E") self.r.save() self.client.login(username="******", password="******") def test_edit_room(self): url = reverse("rooms:edit", kwargs={"room_title": self.r.title}) response = self.client.post(url, { "room-title": self.r.title, "room-unofficial_name": "Starry Night Surprise", "room-description": "Previous home to the best person on earth.", "room-occupancy": 5, "residents-TOTAL_FORMS": 0, "residents-INITIAL_FORMS": 0, "residents-MAX_NUM_FORMS": 50, }, follow=True) url = reverse("rooms:view", kwargs={"room_title": self.r.title}) self.assertRedirects(response, url) self.assertContains(response, "2E") self.assertContains(response, "<dd>{0}</dd>".format(5), html=True) self.assertContains(response, "Starry Night Surprise") self.assertContains( response, "Previous home to the best person on earth.", ) self.assertNotContains(response, self.su.get_full_name()) def test_no_duplicate(self): r = Room.objects.create(title="1A") url = reverse("rooms:edit", kwargs={"room_title": self.r.title}) response = self.client.post(url, { "room-title": r.title, "room-unofficial_name": "", "room-description": "", "room-occupancy": 1, "residents-TOTAL_FORMS": 0, "residents-INITIAL_FORMS": 0, "residents-MAX_NUM_FORMS": 50, }) self.assertEqual(response.status_code, 200) self.assertContains( response, "A room with this title already exists.", ) def test_edit_room_minimal(self): url = reverse("rooms:edit", kwargs={"room_title": self.r.title}) response = self.client.post(url, { "room-title": self.r.title, "room-unofficial_name": "", "room-description": "", "room-occupancy": 5, "residents-TOTAL_FORMS": 0, "residents-INITIAL_FORMS": 0, "residents-MAX_NUM_FORMS": 50, }, follow=True) url = reverse("rooms:view", kwargs={"room_title": self.r.title}) self.assertRedirects(response, url) self.assertContains(response, "<dd>{0}</dd>".format(5), html=True) self.assertNotContains(response, "Starry Night Surprise") self.assertNotContains(response, self.su.get_full_name()) def test_bad_occupancy(self): url = reverse("rooms:edit", kwargs={"room_title": self.r.title}) response = self.client.post(url, { "room-title": self.r.title, "room-unofficial_name": "Starry Night", "room-description": "Home to the best person on earth.", "room-occupancy": -1, "residents-TOTAL_FORMS": 0, "residents-INITIAL_FORMS": 0, "residents-MAX_NUM_FORMS": 50, }) self.assertEqual(response.status_code, 200) self.assertContains( response, "Ensure this value is greater than or equal to 0.", ) response = self.client.post(url, { "title": self.r.title, "unofficial_name": "Starry Night", "description": "Home to the best person on earth.", "occupancy": "", "residents-TOTAL_FORMS": 0, "residents-INITIAL_FORMS": 0, "residents-MAX_NUM_FORMS": 50, }) self.assertEqual(response.status_code, 200) self.assertContains(response, "This field is required.") def test_bad_title(self): url = reverse("rooms:edit", kwargs={"room_title": self.r.title}) response = self.client.post(url, { "room-title": "", "room-unofficial_name": "", "room-description": "", "room-occupancy": 1, "residents-TOTAL_FORMS": 0, "residents-INITIAL_FORMS": 0, "residents-MAX_NUM_FORMS": 50, }) self.assertEqual(response.status_code, 200) self.assertContains(response, "This field is required.") response = self.client.post(url, { "room-title": "2a.", "room-unofficial_name": "", "room-description": "", "room-occupancy": 1, "residents-TOTAL_FORMS": 0, "residents-INITIAL_FORMS": 0, "residents-MAX_NUM_FORMS": 50, }) self.assertEqual(response.status_code, 200) self.assertContains( response, "Only alphanumeric characters are allowed.", ) response = self.client.post(url, { "room-title": "3_", "room-unofficial_name": "", "room-description": "", "room-occupancy": 1, "residents-TOTAL_FORMS": 0, "residents-INITIAL_FORMS": 0, "residents-MAX_NUM_FORMS": 50, }) self.assertEqual(response.status_code, 200) self.assertContains( response, "Only alphanumeric characters are allowed.", )
for room in rooms: try: building = Building.objects.get(pk= reversemap[room['buildingname']]) continue except: print room['buildingname'] continue # Check that we aren't doubling if building.name not in ['Main', 'Bogle', 'North B', 'North C']: continue roomobj = Room(number = room['number'], sqft = room['sqft'], occ = room['occ'], subfree = room['subfree'], numrooms = room['numrooms'], floor = room['floor'], gender = room['gender'], avail = room['avail'], adjacent = room['adjacent'], ada = room['ada'], bi = room['bi'], con = room['con'], bathroom = room['bathroom'], building = building) roomobj.save() print room['number'], building
def setUp(self): self.user = User.objects.get(username='******') self.client.force_authenticate(user=self.user) Room.create(self.ROOM_NUMBER, self.ROOM_CAPACITY, True)
from rooms.models import Track, Artist, Room, Playlist_entry from django.db import transaction ''' execute via ./manage.py shell < name_of_this_script.py ''' start = time() t = start artists_query_set = Artist.objects.all() tracks_query_set = Track.objects.all() tracks_count = tracks_query_set.count() rooms_list = [] #track_artist_list = [] playlist_entries_list = [] for i in range(0, 10000): rooms_list.append(Room(name='room' + str(i))) #for i in range(0, 100000): # artists_list.append(Artist(name='artist'+str(i))) #print('Created 10 000 rooms, 100 000 artists models... ' + str(time()-t) ) #t = time() # create room, artists BEFORE using # foreign key to them while creating tracks and rooms Room.objects.bulk_create(rooms_list) #Artist.objects.bulk_create(artists_list) #print('Created db rows for rooms, artists... ' + str(time()-t) ) #t = time()
mapfile = open('reversemap.dat') reversemap = pickle.load(mapfile) for room in rooms: try: building = Building.objects.get(pk=reversemap[room['buildingname']]) continue except: print room['buildingname'] continue # Check that we aren't doubling if building.name not in ['Main', 'Bogle', 'North B', 'North C']: continue roomobj = Room(number=room['number'], sqft=room['sqft'], occ=room['occ'], subfree=room['subfree'], numrooms=room['numrooms'], floor=room['floor'], gender=room['gender'], avail=room['avail'], adjacent=room['adjacent'], ada=room['ada'], bi=room['bi'], con=room['con'], bathroom=room['bathroom'], building=building) roomobj.save() print room['number'], building