def save_puzzle(user, number, ipuz, public): """Save a puzzle in ipuz format to the database.""" puzzle_data = json.loads(ipuz) pub_date = timezone.now() if public else default_pub_date() # Remove any old data existing = Puzzle.objects.filter(user=user, number=number) if existing: existing[0].delete() # Create a new puzzle puz = Puzzle(user=user, number=number, pub_date=pub_date, size=puzzle_data['dimensions']['width']) puz.save() # Extract entries from the ipuz data for direction in [{ 'name': 'Across', 'down': False }, { 'name': 'Down', 'down': True }]: for entry in puzzle_data['clues'][direction['name']]: pos = get_start_position(puzzle_data['puzzle'], entry['number']) answer = get_answer(puzzle_data, entry, direction['down'], pos) entry = Entry(puzzle=puz, clue=escape(entry['clue']), answer=answer, x=pos['x'], y=pos['y'], down=direction['down']) entry.save()
def create_puzzle_from_url(url): img_response = urllib2.urlopen(root_url + url) filename = img_response.geturl().split('/')[-1] puzzle = Puzzle(key='') try: puzzle.image.save(filename, SimpleUploadedFile(filename, img_response.read(), content_type='image/jpg'), save=True) puzzle.save() except Exception as ex: puzzle.delete() print ex
def index(request): """ Create random puzzle """ # http://elpenia.wordpress.com/2010/05/11/getting-random-objects-from-a-queryset-in-django/ count = Quote.objects.all().count() slice = int(random.random() * count) thisquote = Quote.objects.all()[slice] ## PostgreSQL does not have consequitive IDs, so have to get them all idlist = [p.id for p in Person.objects.all()] authorid = thisquote.author.id idlist.remove(authorid) fakes = random.sample(idlist, 3) fakepeeps = Person.objects.filter(id__in=fakes) newpuzzle = Puzzle(quote=thisquote, fakeauth0=fakepeeps[0], fakeauth1=fakepeeps[1], fakeauth2=fakepeeps[2], ) newpuzzle.save() return showpuzzle(request, newpuzzle)