def ans(request): errors =[] if not request.user.is_authenticated(): errors.append("You need to login") return erquestion(request, errors) else: try: q_id = request.GET['id'] if request.method == 'POST': form = AnswerForm(request.POST) if form.is_valid(): cd = form.cleaned_data u = request.user q = Question.objects.get(id = q_id) a = Answer(author = u, question = q, answer_date = timezone.now(), content = cd['content'], isright = False, rating = 0) a.save() body = cd['content'] send_email('%s answer to your question, %s' % (u.username , q.user.username), body, [q.user.email]) return HttpResponseRedirect("/answers/?id=" + str(q_id)) except Question.DoesNotExist: errors.append("Wrong id") return erquestion(request, errors) except KeyError: errors.append("No id field in get request") return erquestion(request, errors) except: errors.append("Something goes wrong") return erquestion(request, errors) return HttpResponseRedirect("/answers/?id=" + str(q_id))
def handle(self, *args, **options): fake = Factory.create() min_number = int(options['min_number']) max_number = int(options['max_number']) users = User.objects.all()[1:] questions = Question.objects.all() is_correct = (True, False) counter = 1 for q in questions: for i in range(0, randint(min_number, max_number)): ans = Answer() ans.text = fake.paragraph(nb_sentences=randint(2, 4), variable_nb_sentences=True) ans.user = choice(users) ans.question = q ans.rating = randint(0, 1500) ans.is_correct = choice(is_correct) ans.id = counter counter += 1 ans.save() self.stdout.write('in question [%d] add ans [%d]' % (q.id, ans.id))
def fill_db(self): for i in range(0, 30): usr = User(username='******' + str(i), password='******' + str(i), first_name='User') usr.save() prof = Profile(avatar='avatar.jpeg', user=usr) prof.save() try: tbag = Tag.objects.get(name='Bucket' + str(i % 20)) tbag.popularity += 1 except Exception: tbag = Tag(name='Bucket' + str(i % 20), popularity=1) tbag.save() quest = Question(title=str(i) + 'bucket', text='see my bucket, I have a' + str(10000 - i) + ' bucket remains', author=prof, votes=i) quest.save() quest.liked.add(prof) quest.tag.add(tbag) for j in range(0, 20): ans = Answer(text='Test answer' + str(i), author=prof, question=quest) ans.votes = int(((i + j) * 6) % 40) ans.save() ans.voted.add(prof)
def generateAnswers(n): for i in range(n): start = [ "Do ", "Get ", "Leave ", "Remove ", "Press ", "Don't ", "Use ", "EXTERMINATE!!!! ", "Kill ", "Banish ", "Love ", "Hug ", "Complete ", "Do ", "Make ", "Enjoy ", "Start ", "Delete ", "Keep Calm " ] mid = [ "a barrel roll", "your mom", "the configs", "the Force", "the attack", "that RED button", "your wits", "WD-40", "duct tape", "card", "EXTERMINATE!!! ", "some noise", "the show", "and go on" ] end = [ ", Luke.", ", noob!", ", man!", " or you're screwed.", "!", "br@h!", "EXTERMINATE?!" ] + [".", "?", "!"] * 2 ansText = random.choice(start) + random.choice(mid) + random.choice( end) + '(' + str(random.randint(1, 1000000)) + ')' author = UserAccount.objects.all().order_by('?')[0] approved = random.choice([True] + 5 * [False]) question = Question.objects.all().order_by('?')[0] ans = Answer(content=ansText, author=author, approved=approved, question=question) ans.save() if i % 500 == 0: print i
def handle(self, *args, **options): user = User.objects.get(email='*****@*****.**') list_tags = ["Perl", "Python", "TechnoPark", "MySQL", "Django", "Mailru", "Voloshin", "Firefox", "black-jack", "bender"] Question.objects.all().delete() Answer.objects.all().delete() Tag.objects.all().delete() for i in range(0, 100): q=Question( author=user, body='body ' + str(i), title = 'title ' + str(i), ) q.save() for j in range(1, 3): a=Answer( text='answer ' + str(i) + ' ' + str(j), author=user, question=q, ) a.save() tmp = i%10 t=Tag( name = list_tags[tmp], rating = tmp, ) t.save() t.question.add(q)
def add_answer(request): q = get_object_or_404(Question, pk=2) u = get_object_or_404(User, pk=12) for i in range(5000, 10000): answer = Answer(ansver_text=int(i), customuser=u.customuser, question=q, pub_data=timezone.now(), flag=0) answer.save() return HttpResponseRedirect(reverse("questions"))
def question(request, question_id): if request.method == "GET": q = get_object_or_404(Question, pk=question_id) a = q.answer_set.all() answer_list = paginator(request, a, 2) form = answerform() return render( request, 'ask/question.html', { 'question': q, 'answer_list': answer_list, 'tags': Tag.objects.besters(), 'question_list': answer_list, 'users': Author.objects.all(), 'form': form, }) if request.method == "POST": q = get_object_or_404(Question, pk=question_id) form = answerform(request.POST) if form.is_valid(): a = Answer(question=q, text=form.cleaned_data['text'], title=form.cleaned_data['title'], author=request.user.author, correct=False, pub_date=timezone.now()) a.save() return HttpResponseRedirect( reverse('ask:question', kwargs={'question_id': question_id}))
def create_answers(users, questions): for i in range(0, 1000000): uid = random.randint(0, len(users) - 1) qid = random.randint(0, len(questions) - 1) answer = Answer(contents="Просто ответ :|", question=questions[qid], author=users[uid], date_created=timezone.now()) answer.save()
def handle(self, *args, **options): u = User.objects.get(id=1) q = Question.objects.get(id=8) a = Answer(question = q, text = u'Новый ответ!)!)', author = u, ) a.save()
def drop(self): fx_users = User.find({"username": re.compile(r"^fx_test_user")}) user_ids = [u._id for u in fx_users] ctx.log.info("dropping fixture comments") Comment.destroy_many({"author_id": {"$in": user_ids}}) ctx.log.info("dropping fixture answers") Answer.destroy_many({"author_id": {"$in": user_ids}}) ctx.log.info("dropping fixture questions") Question.destroy_many({"author_id": {"$in": user_ids}}) ctx.log.info("dropping fixture users") User.destroy_many({"username": re.compile(r"^fx_test_user")})
def _fill_answer(self): print('FILLING ANSWER MODEL...') for ix in range(500): temp_answer = Answer(question=np.random.choice( Question.objects.all()), text='Answer{}'.format(ix), rating=np.random.normal(scale=20), creation_date=timezone.now(), edit_date=timezone.now(), is_correct=False) temp_answer.save() print('ADDED {} ANSWERS'.format(Answer.objects.count()))
def handle(self, *args, **options): n = int(args[0]) qn = Question.objects.count() qu = User.objects.count() for i in range(1, n): user = User.objects.get(id = random.randint(1, qu)) try: a = Answer(content = self.fake.text(random.randint(50, 400)), qst = Question.objects.get(id = random.randint(1, qn)), user = user, date = self.fake.date(user.reg_date.month, user.reg_date.year), flag = False, raiting=0) a.save() except Question.DoesNotExist: print("Question does not exist")
def answer(request): if (request.method == "POST"): form = NewAnswerForm(request.POST) if (form.is_valid): uscontent = request.POST["content"] ususer = User.objects.get(username=request.user.username) usquestionID = int(request.POST["question"]) usquestion = Question.objects.get(id=usquestionID) answ = Answer(content=uscontent, question=usquestion, author=ususer) answ.save() return questionID(request, usquestionID) else: return redirect('/question')
def handle(self, *args, **options): text = options['text'] try: question = Question.objects.get(pk=options['q_id']) except Question.DoesNotExist: raise CommandError("Question %d doesn't exist" % options['q_id']) try: user = Profile.objects.get(user_id=options['author_id']) except Profile.DoesNotExist: raise CommandError("User %d doesn't exist" % options['author_id']) answer = Answer(text=text, author=user, question=question) answer.save()
def ajaxAnswer(request): if request.is_ajax(): dataJSON = simplejson.loads(request.raw_post_data) textData = dataJSON["text"] userData = User.objects.get(id=dataJSON["author"]) questionData = Question.objects.get(id=dataJSON["question"]) answ = Answer(content=textData, question=questionData, author=userData) answ.save() notif = Notifications(user=questionData.author, answer=answ, answer_comment=False) notif.save() mailNotify(notif) return HttpResponse("success") else: redirect('/question')
def handle(self, *args, **options): (amount,) = args count = int(amount) countOfQuestions = Question.objects.count() #EXCEPTIONS if count < 1: raise ValueError('incorrect parameter') if countOfQuestions == 0: raise ValueError('table of questions is empty. You must add questions!') firstQuestionID = Question.objects.first().id lastQuestionID = Question.objects.last().id firstUserID = User.objects.first().id lastUserID = User.objects.last().id createdAnswers=0 #generate answers for i in range(count): while True: try: q = Question.objects.get(id=random.randint(firstQuestionID , lastQuestionID)) break except ObjectDoesNotExist: continue while True: try: u = User.objects.get(id=random.randint(firstUserID + 1, lastUserID)) #without admin user break except ObjectDoesNotExist: continue a_text = randomText(random.randint(3,30)) answ = Answer(question = q, text = a_text, author=u, isRight=bool(random.randint(0,1)), rating=0) answ.save() createdAnswers+=1 print('was created : ' + str(createdAnswers) + ' answers') print('==============================================') print('was created : ' + str(createdAnswers) + ' answers') # question = models.ForeignKey(Question) # text = models.TextField() # author = models.ForeignKey(User) # createdData = models.DateTimeField(default=timezone.now()) # isRight = models.BooleanField(default=False) # rating = models.IntegerField(default=0)
def add_answer(request): try: data = request.POST qid = int(data['qid']) content = data['content'] a = Answer(text=content, author=request.profile, question_id=qid) a.save() ans_html = str(render_to_response('a.html', {'answer': a}).content) post('https://alex-erm.ru/pub?id=' + str(qid), ans_html) return JsonResponse(data={'status': 'OK', 'id': a.id}) except Exception: return JsonResponse(data={ 'status': 'error', 'msg': 'incorrect request' })
def restore_answer_comment(question_id, answer_id, comment_id): c: Optional[Comment] = Comment.get(comment_id, "comment not found") a: Optional[Answer] = Answer.get(answer_id, "comment not found") q: Optional[Question] = Question.get(question_id, "comment not found") if a.parent_id != q._id or c.parent_id != a._id: raise NotFound("comment not found") restore_post(c) return json_response({"data": c.api_dict(COMMENT_FIELDS)})
def accept_answer(question_id, answer_id): u: User = get_user_from_app_context() q: Optional[Question] = Question.get(question_id, "answer not found") a: Optional[Answer] = Answer.get(answer_id, "answer not found") if a.parent_id != q._id: raise NotFound("answer not found") if q.author_id != u._id: raise Forbidden("only question's author can accept answers") q.set_accepted_answer(a) return json_response({"data": a.api_dict(ANSWER_FIELDS)})
def answers(req): c = 30 first_range = range(1, 6) if not "name" in req.session: return HttpResponse('{"status":"error","code":"5"}'); #Only for registered users if "qst" in req.POST and "text" in req.POST: qst_id = req.POST['qst'] text = req.POST['text'] # handling a text if qst_id and text: try: q = Question.objects.get(id = qst_id) u = User.objects.get(id=req.session["name"]) d = datetime.datetime.now() a = Answer(content = text, qst = q, user = u, date = "{0}-{1}-{2}".format(d.year, d.month, d.day) , flag = False, raiting = 0) a.save() lng = Answer.objects.filter(qst = qst_id).count() total = int(math.ceil(float(lng) / c)) # Number of pages (All pages) res = Answer.objects.filter(qst = qst_id)[(total - 1) * c : lng] s = "" for i in res: try: s = s + '{{"id":"{0}", "content":"{1}", "user":"******", "date":"{3}", "raiting":"{4}", "user_name":"{5}"}},'.format(i.id, i.content, i.user.id, i.date.strftime("%h %d, %Y"), i.raiting, i.user.name) except: s = s + '{{"id":"{0}", "content":"{1}", "user":"******", "date":"{3}", "raiting":"{4}", "user_name":"{5}"}},'.format(i.id, i.content, i.user.id, i.date, i.raiting, i.user.name) s = s[0:-1] show_first = True start = total - 3 end = total if total in first_range: show_first = False start = 1 pag = '{{"show_first":"{0}", "start": "{1}", "end": "{2}"}}'.format(show_first, start, end); return HttpResponse('{{"status":"ok","asw":[{0}], "total":"{1}", "pag":{2}}}'.format(s, total, pag)) except (Question.DoesNotExist, Answer.DoesNotExist, User.DoesNotExist): return HttpResponse('{"status":"error","code":"3"}') #Question or User Doesn't exist return HttpResponse('{"status":"error","code":"4"}')
def setup(): f = Faker() tags = f.words(nb=20) for i in tags: a = Tag(tag=i) a.save() for i in range(100): tt = f.text(50) te = f.text() a = Question(title=tt, text=te, author_id=randint(2, 4)) a.save() a.tags.add(randint(1, 20), randint(1, 20), randint(1, 20)) for i in range(300): te = f.text() an = Answer(text=te, author_id=randint(2, 4), question_id=randint(1, 100)) an.save()
def generate_answers(n): arr = open('/home/hase/technopark/web/AskZaytsev/scripts/text.txt', 'r').read().split(' ') asize = len(arr) ucount = Profile.objects.count() qcount = Question.objects.count() for i in range(0, n): print(i) word_cnt = random.randint(20, 50) text = '' title = arr[random.randint(0, asize - 1)] + ' ' + str(i) own = Profile.objects.filter(id=random.randint(1, ucount))[0] for j in range(0, word_cnt): text += arr[random.randint(0, (asize - 1))] + ' ' q = Question.objects.filter(id=random.randint(1, qcount))[0] a = Answer(owner=own, question=q, title=title, text=text) a.save() print('ans')
def answer(request, question_id): answer = Answer.answers.answer(question_id) during_question = Question.questions.question(question_id) if request.POST: form = AnswerForm(request.POST) if form.is_valid(): text = form.cleaned_data.get('text') author = request.user question = during_question a = Answer( text = text, author = author, question = question) a.save() return redirect('/') form = AnswerForm() return render(request, 'answer.html', { 'answers' : answer, 'question' : during_question, 'form' : form })
def answer(request, pk): form = NewAnswer() num_answer_on_page = 3 pk = int(pk) question = Question.objects.get(id=pk) new_answer = False position_of_answ = 0 if request.POST: text = request.POST.get('text') if text != '': a = Answer(question = question, text = text, author = request.user) a.save() new_answer = True position_of_answ = a.id if new_answer: request.GET = {'page': 'last'} answers_list = Answer.objects.filter(question__id=pk) answers = paginateObjects(request, answers_list, num_answer_on_page) pag = paginatorIndex(answers.number, answers.paginator.num_pages) #print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" #print pag['dotFirst'] #print pag['pr'] #print answers.number #print pag['ne'] #print pag['dotLast'] context = { 'question': question, 'answers': answers, 'pag': pag, 'form': form, 'new_asnwer': new_answer, 'position': position_of_answ } #return redirect('/answer/' + str(pk)) return render(request, 'answer.html', context)
def create_answer_comment(question_id, answer_id): a: Optional[Answer] = Answer.get(answer_id, "answer not found") if a.parent_id != resolve_id(question_id): raise NotFound("answer not found") user: User = get_user_from_app_context() attrs = request.json if "body" not in attrs: raise ApiError("body is missing") c = a.create_comment({"body": attrs["body"], "author_id": user._id}) c.save() return json_response({"data": c.api_dict(COMMENT_FIELDS)})
def revoke_answer(question_id, answer_id): u: User = get_user_from_app_context() q: Optional[Question] = Question.get(question_id, "answer not found") a: Optional[Answer] = Answer.get(answer_id, "answer not found") if a.parent_id != q._id: raise NotFound("answer not found") if q.author_id != u._id: raise Forbidden("only question's author can revoke answers") if not a.accepted: raise NotAccepted("answer is not accepted so can't be revoked") q.set_accepted_answer(None) a.reload() return json_response({"data": a.api_dict(ANSWER_FIELDS)})
def newanswer(request, question_id): if request.user.is_authenticated(): q = get_object_or_404(Question, pk=question_id) u = request.user user = u.customuser answer_form = AnswerForm(request.POST) # A form bound to the POST data if answer_form.is_valid(): # All validation rules pass answer = Answer( ansver_text=answer_form.cleaned_data["ansver_text"], customuser=user, question=q, pub_data=timezone.now(), flag=0, ) answer.save() request.session["message"] = "Your question was successfully added!!" request.session["flag"] = 1 else: request.session["message"] = "Error!!" request.session["flag"] = 1 else: request.session["message"] = "You must be logged in" request.session["flag"] = 0 return HttpResponseRedirect(reverse("detail", args=(question_id,))) # Redirect after POST
def handle(self, *args, **options): User.objects.all().delete() user = User.objects.create_user("nuf", "*****@*****.**", "nuf") user.save() tagmas = [ 'ActionScript', 'Ada', 'Bash', '(Visual) Basic', 'Bourne Shell', 'Bro', 'C', 'C Shell', 'C#', 'C++', 'Curl', 'Fortran', 'Go', 'Haskell', 'Java', 'JavaScript', 'Lisp', 'Maple', 'Mathematica', 'MATLAB', 'MOO', 'Objective-C', 'Pascal', 'Perl', 'PHP', 'Python', 'Ruby', 'Simulink', 'Verilog', 'VHDL' ] Question.objects.all().delete() Tags.objects.all().delete() for i in range(1, 10): q = Question( author=user, text= 'In eget neque in turpis suscipit tristique vitae nec mauris. Vestibulum auctor, turpis non lobortis gravida, nisi est vulputate lectus, ut dictum erat augue ut erat.', title='title' + str(i), question_id=i, ) q.save() t1 = Tags(name=tagmas[(i - 1) * 2]) t2 = Tags(name=tagmas[(i - 1) * 2 + 1]) t1.save() t2.save() t1.question.add(q) t2.question.add(q) for j in range(1, 10): a = Answer( text= 'In eget neque in turpis suscipit tristique vitae nec mauris. Vestibulum auctor, turpis non lobortis gravida, nisi est vulputate lectus, ut dictum erat augue ut erat. In fringilla tincidunt dolor, at pulvinar lacus cursus nec. Pellentesque ultrices eget odio ac ullamcorper. Duis turpis orci, tempor vel massa id, posuere condimentum purus. Sed rutrum magna non nisi posuere interdum. Vivamus eget diam dictum mi malesuada accumsan.', author=user, question=q, ) a.save()
def vote_answer(question_id, answer_id): a: Optional[Answer] = Answer.get(answer_id, "answer not found") if a.parent_id != resolve_id(question_id): raise NotFound("answer not found") u: User = get_user_from_app_context() if a.author_id == u._id: raise Forbidden("you can't vote for your own answers") attrs = request.json if "value" not in attrs: raise ApiError("value field is mandatory") Vote.vote(a._id, u._id, attrs["value"]) a.reload() return json_response({"data": a.api_dict(fields=ANSWER_FIELDS)})
def detail(request,question_id): if request.method == "POST": if not request.user.is_authenticated: return redirect('askCommunity:login') question = Question.objects.get(question_id = question_id) answer = Answer() answer.question_id = question answer.answer = request.POST.get('answer') answer.answered_by = Profile.objects.get(user = request.user) answer.save() else: question = Question.objects.get(question_id = question_id) all_answers = Answer.objects.filter(question_id = question_id) context = {'question' : question, 'answers' : all_answers} return render(request,'detail.html',context = context)
def vote_answer_comment(question_id, answer_id, comment_id): c: Optional[Comment] = Comment.get(comment_id, "comment not found") a: Optional[Answer] = Answer.get(answer_id, "comment not found") q: Optional[Question] = Question.get(question_id, "comment not found") if a.parent_id != q._id or c.parent_id != a._id: raise NotFound("comment not found") u: User = get_user_from_app_context() if c.author_id == u._id: raise Forbidden("you can't vote for your own comments") attrs = request.json if "value" not in attrs: raise ApiError("value field is mandatory") Vote.vote(c._id, u._id, attrs["value"]) c.reload() return json_response({"data": c.api_dict(fields=COMMENT_FIELDS)})
def handle(self, *args, **options): fake = Factory.create() min_number = int(options['min_number']) max_number = int(options['max_number']) users = User.objects.all()[1:] questions = Question.objects.all() for q in questions: for i in range(0, randint(min_number, max_number)): ans = Answer() ans.text = fake.paragraph(nb_sentences=randint(2, 10), variable_nb_sentences=True) ans.auth = choice(users) ans.question = q ans.save()
def answer_add(request): ask_id = str(request.META.get('HTTP_REFERER', "/").split('/')[-2]) answer = Answer() # return HttpResponse(ask_id) answer.ask_id = ask_id if request.method == 'POST': af = AnswerForm(request.POST) if af.is_valid(): # 获取表单内容 content = af.cleaned_data['answer'] answer.content = content answer.save() return render_to_response('ask/answer_add_done.html', {'content': content}) else: af = AnswerForm() return render_to_response('ask/answer_add.html', {'af': af})
def restore_answer(question_id, answer_id): a: Optional[Answer] = Answer.get(answer_id, "answer not found") if a.parent_id != resolve_id(question_id): raise NotFound("answer not found") restore_post(a) return json_response({"data": a.api_dict(ANSWER_FIELDS)})
def create_qusetion_answer_and_connect_user(how_many): does_NOT_exist_users = '' for j in range(how_many): ### User get random user_id = random.randint(1, 10362) try: u = User.objects.get(id=user_id) except: does_NOT_exist_users = does_NOT_exist_users + str(user_id) + ' ' user_id = random.randint(1, 10362) try: u = User.objects.get(id=user_id) except: does_NOT_exist_users = does_NOT_exist_users + str(user_id) + ' ' user_id = random.randint(1, 10362) u = User.objects.get(id=user_id) ### End User get random ### Tag create start_tag_lenght = 3 end_tag_lenght = 6 t_text = randomword(start_tag_lenght, end_tag_lenght) t = Tag(text = t_text) t.save() ### End Tag create ### Question create question_length_low = 8 question_length_high = 15 q_title = randomword(question_length_low, question_length_high) for i in range(random.randint(0, 2)): q_title = q_title + ' ' + randomword(question_length_low, question_length_high) q_title = q_title + '?' q_text = randomword(question_length_low, question_length_high) for i in range(random.randint(3, 20)): q_text = q_text + ' ' + randomword(question_length_low, question_length_high) q_rating = random.randint(-10, 150) q = Question(title = q_title, text = q_text, author = u, rating = q_rating ) q.save() q.tags.add(t) q.save() ### End Question create ### User get random ser_id = random.randint(1, 10362) try: u = User.objects.get(id=user_id) except: does_NOT_exist_users = does_NOT_exist_users + str(user_id) + ' ' user_id = random.randint(1, 10362) try: u = User.objects.get(id=user_id) except: does_NOT_exist_users = does_NOT_exist_users + str(user_id) + ' ' user_id = random.randint(1, 10362) u = User.objects.get(id=user_id) ### End User get random ### Answer create answer_length_low = 8 answer_length_high = 15 a_text = randomword(answer_length_low, answer_length_high) for i in range(random.randint(7, 25)): a_text = a_text + ' ' + randomword(answer_length_low, answer_length_high) a_right_answer = True a = Answer(question = q, text = a_text, right_answer = a_right_answer, author = u ) a.save() ### End asnwer create print('Create: ' + str(j)) print('Create: ' + str(how_many)) print(does_NOT_exist_users)
def handle(self, *args, **options): # User.objects.all().delete() # Tag.objects.all().delete() # Profile.objects.all().delete() # Question.objects.all().delete() # Answer.objects.all().delete() # Like.objects.all().delete() try: u = User.objects.get(username='******') except: u = User.objects.create(username='******', first_name='test', email='*****@*****.**') u.set_password('test') u.save() p = Profile.objects.create(user_id=u.id, rating=20) item_list = [] for i in range(0, int(options['users'])): u = User(username=randomword(9) + str(i), first_name=randomword(3) + str(i), email=randomword(10) + str(i) + '@aithelle.com') item_list.append(u) if i % 10000 == 0: User.objects.bulk_create(item_list) item_list = [] User.objects.bulk_create(item_list) um = User.objects.aggregate(Min('id'), Max('id')) item_list = [] for i in range(0, int(options['users'])): p = Profile(user_id=um['id__max'] - i, rating=random.randint(0, 20)) item_list.append(p) if i % 10000 == 0: Profile.objects.bulk_create(item_list) item_list = [] Profile.objects.bulk_create(item_list) print 'Users created\n' item_list = [] for i in range(0, int(options['tags'])): t = Tag(text=randomword(5)) item_list.append(t) if i % 10000 == 0: Tag.objects.bulk_create(item_list) item_list = [] Tag.objects.bulk_create(item_list) tm = Tag.objects.aggregate(Min('id'), Max('id')) print 'Tags created\n' for i in range(0, int(options['questions'])): q = Question(author_id=random.randint(um['id__min'], um['id__max']), title=randomword(20), text=randomword(10) + ' ' + randomword(20), rating=random.randint(-100, 100)) q.save() q.tags.add(random.randint(tm['id__min'], tm['id__max']), \ random.randint(tm['id__min'], tm['id__max']), \ random.randint(tm['id__min'], tm['id__max'])) qm = Question.objects.aggregate(Min('id'), Max('id')) print 'Questions created\n' item_list = [] for i in range(0, int(options['answers'])): a = Answer(author_id=random.randint(um['id__min'], um['id__max']), question_id=random.randint(qm['id__min'], qm['id__max']), is_right=random.randint(0, 1), text=randomword(10) + ' ' + randomword(10), rating=random.randint(-100, 100)) item_list.append(a) if i % 10000 == 0: Answer.objects.bulk_create(item_list) item_list = [] Answer.objects.bulk_create(item_list) am = Answer.objects.aggregate(Min('id'), Max('id')) print 'Answers created\n' item_list = [] for i in range(0, int(options['likes'])): item_type = random.choice(['question', 'answer']) if item_type == 'question': item = random.randint(qm['id__min'], qm['id__max']) else: item = random.randint(am['id__min'], am['id__max']) l = Like(author_id=random.randint(um['id__min'], um['id__max']), item_type=item_type, item=item, is_like=random.randint(0, 1)) item_list.append(l) if i % 20000 == 0: Like.objects.bulk_create(item_list) item_list = [] Like.objects.bulk_create(item_list) print 'Likes created\n'
def handle(self, *args, **options): user_range = 25 ask_range = 37 answers_range = 97 f_name = [ 'Red', 'Mad', 'Dummy', 'Crazy', 'Big', 'Black', 'Lonely', 'Shiz', 'Drunken', 'Wicked', 'Brainless', 'Rich', 'Stubborn', 'Stupid', 'Fat', 'Wooden', 'Donald', 'American', 'Dead', 'Lucky', 'Night' ] l_name = [ 'Sailor', 'Rat', 'Man', 'Rabbit', 'Donkey', 'Policeman', 'Child', 'Penguin', 'Joker', 'Lawmaker', 'Judge', 'Iron', 'President', 'Trump', 'Duck', 'Timmy', 'Kartman', 'Kenny', 'Orc', 'Illuminati', 'Band', 'Slave', 'Coffee', 'Aviato', 'Redneck', 'Camper', 'King' ] for i in range(0, user_range): username = u'{0}{1}'.format( f_name[random.randrange(0, len(f_name))], l_name[random.randrange(0, len(l_name))]) email = u'{0}@e-corp.com'.format(username) password = u'{0}123'.format(username) try: User.object.create_user(username=username, email=email, password=password) except: username = u'{0}{1}'.format(username, i) email = u'{0}@e-corp.com'.format(username) User.object.create_user(username=username, email=email, password=password) tags_list = [ 'LOL', 'mad', 'wazzzup', 'DonaldTrump', 'luxury', 'shaurma', 'Skynet', 'TheyAreWatchingYou', 'illuminati', 'Futurama', 'Bender', 'BlackJack', 'TacoBell', 'BreakingBad', ] for tag in tags_list: try: new_tag = Tag() new_tag.title = tag new_tag.save() except: pass f_question = ['How to', 'Why to', 'Can I', 'What if'] l_question = ['fly', 'run', 'jump', 'degrade', 'capture the world'] users = User.object.all() users_count = len(users) tags_list = Tag.objects.all() tags_count = len(tags_list) for i in range(0, ask_range): ask = Ask() random_pk = random.randrange(1, users_count) ask.author = users[random_pk] ask.question = u'{0} {1}'.format( f_question[random.randrange(0, len(f_question))], l_question[random.randrange(0, len(l_question))]) ask.text = u'{0} question by {1}'.format(ask.question, ask.author.username) ask_tags = [] tags_range = random.randrange(1, 4) for i in range(0, tags_range): ask_tags.append(tags_list[random.randrange(0, tags_count)]) ask.rating = random.randrange( -10, 30) # temporary remove later by UserVote ask.save() ask.tags = set(ask_tags) ask.save() asks = Ask.objects.all() asks_count = len(asks) f_answer = ['Just', 'I dont', 'May be', 'You should'] l_answer = ['do it', 'know', 'know', 'forget it'] for i in range(0, answers_range): answer = Answer() random_pk = random.randrange(1, users_count) answer.author = users[random_pk] ask_pk = random.randrange(1, asks_count) answer.ask = asks[ask_pk] answer.text = u'{0} {1}'.format( f_answer[random.randrange(0, len(f_answer))], l_answer[random.randrange(0, len(l_answer))]) answer.save()