def save(self): author = User.objects.get(username=self.cleaned_data['author']) question = Question(title=self.cleaned_data['title'], text=self.cleaned_data['text'], author=author) question.save() return question
def ask(request): """Ask form.""" if request.method == 'POST': form = AskForm(request.POST) if form.is_valid(): params = { 'title': form.cleaned_data['title'], 'text': form.cleaned_data['text'] } if request.user.is_authenticated(): params.update({'author': request.user}) question = Question(**params) question.save() return HttpResponseRedirect( reverse('question', kwargs={'id': question.id}) ) else: form = AskForm() context = {'form': form} return render(request, 'ask.html', context)
def save(self): #question = Question(**self.cleaned_data) title = self.cleaned_data['title'] text = self.cleaned_data['text'] question = Question(title=title, text=text, author=self._user) question.save() return question
def save(self): q = Question(**self.cleaned_data) q.save() return q
def save(self): if self._user.is_anonymous(): self.cleaned_data['author_id'] = 1 else: self.cleaned_data['author'] = self._user ask = Question(**self.cleaned_data) ask.save() return ask
def test_model(request, *args, **kwargs): user = User(username='******', password='******') user.save() question = Question(title='qwe', text='qwe', author=user) question.save() answer = Answer(text='qwe', question=question, author=user) answer.save() return HttpResponse('OK', status=200)
def save(self): user = User.objects.get(id=3) self.cleaned_data['author'] = user self.cleaned_data['added_at'] = datetime.now() question = Question(**self.cleaned_data) question.save() return question
def save(self): #question =Question(**self.cleaned_data) new_qs = Question( text=self.cleaned_data['text'], title=self.cleaned_data['title'], author=self._user ) new_qs.save() return new_qs
def create(self, validated_data): qobj = Question() qobj.topic = validated_data['topic'] qobj.detail = validated_data['detail'] user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user uobj = Euser.objects.get(username=str(user.username)) qobj.user = uobj qobj.save() for t in validated_data['tags_list']: try: cobj = Category.objects.get(tag=t) except Category.DoesNotExist: cobj = None if cobj is not None: qobj.tag_list.add(cobj) qobj.save() return qobj
def testQuestion(self): from qa.models import Question # question = Question.object.create() # assert False, "Test" user, _ = User.objects.get_or_create(username='******', password='******') try: question = Question(title='qwe', text='qwe', author=user) question.save() except: assert False, "Failed to create question model" assertIsNone(question.id, 'question id is None')
def save(self): data = { 'title': self.cleaned_data['title'], 'text': self.cleaned_data['text'], 'added_at': datetime.now().strftime("%Y-%m-%d %H:%M:%S"), 'rating': 0, 'author_id': self._user.id, } question = Question(**data) question.save() return question
def ask_question(request): if request.method == 'POST': form = AskForm(request.POST) if form.is_valid(): new_question = Question(**form.cleaned_data) new_question.save() return HttpResponseRedirect( reverse('qa:question', kwargs={'id': new_question.id})) else: form = AskForm() return render(request, 'qa/question_new.html', {'form': form})
def test_question(self): from qa.models import Question try: title = Question._meta.get_field('title') except FieldDoesNotExist: assert False, "title field does not exist in Question model" assert isinstance(title, CharField), "title field is not CharField" try: text = Question._meta.get_field('text') except FieldDoesNotExist: assert False, "text field does not exist in Question model" assert isinstance(text, TextField), "text field is not TextField" try: added_at = Question._meta.get_field('added_at') except FieldDoesNotExist: assert False, "added_at field does not exist in Question model" assert isinstance(text, DateField) or isinstance( added_at, DateField), "added_at field is not DateTimeField" try: rating = Question._meta.get_field('rating') except FieldDoesNotExist: assert False, "rating field does not exist in Question model" assert isinstance(rating, IntegerField), "text field is not IntegerField" try: author = Question._meta.get_field('author') except FieldDoesNotExist: assert False, "author field does not exist in Question model" assert isinstance(author, ForeignKey), "author field is not ForeignKey" if hasattr(author, 'related'): assert author.related.parent_model == User, "author field does not refer User model" elif hasattr(author, 'rel'): assert author.rel.to == User, "author field does not refer User model" try: likes = Question._meta.get_field('likes') except FieldDoesNotExist: assert False, "likes field does not exist in Question model" assert isinstance( likes, ManyToManyField), "likes field is not ManyToManyField" if hasattr(likes, 'related'): assert likes.related.parent_model == User, "likes field does not refer User model" elif hasattr(likes, 'rel'): assert likes.rel.to == User, "likes field does not refer User model" user, _ = User.objects.get_or_create(username='******', defaults={ 'password': '******', 'last_login': timezone.now() }) try: question = Question(title='qwe', text='qwe', author=user) question.save() except: assert False, "Failed to create question model, check db connection"
def save(self): # questions = Question(**self.cleaned_data) # questions.author_id = 1 # questions.save() # return questions if self._user.is_anonymous(): self.cleaned_data['author_id'] = 1 else: self.cleaned_data['author'] = self._user question = Question(**self.cleaned_data) question.save() return question
def perform_destroy(self, instance): question = Question() qs = question.collection.find( {"comments": { "$all": [str(instance.get("_id"))] }}) if qs.count() == 1: question_obj = qs.next() comments = question_obj.get("comments") # delete comment id from question comment list comments.remove(str(instance.get("_id"))) data = {"comments": comments} question.update({"_id": question_obj.get("_id")}, data) self.comment.remove({"_id": instance.get("_id")})
def has_object_permission(self, request, view, obj): question_id = obj question = Question() qs = question.collection.find({"_id": ObjectId(question_id)}) if qs.count() == 1: return True return False
def save(self): question = Question(title=self.cleaned_data['title'], text=self.cleaned_data['text'], author=self.profile_user, short_text=Question.cut_text( self.cleaned_data['text'])) question.save() self.profile_user.questions_count += 1 self.profile_user.save() tags = self.cleaned_data["tags"].replace(",", " ") tags = sub(r"[^\w\s]", "", tags) tags = sub(r"\s+", " ", tags) for tag in tags.split(" "): Tag.objects.add(tag_name=tag, question=question) return question
def count_question_views(): settings.configure() time = timezone.now() - timedelta(days=1) question = Question() question_views = QuestionViews() qs = question_views.collection.find({"created_at": {"$gte": time}}) for qv in qs: question_id = qv.get("question_id") question.collection.update_one({"_id": question_id}, {"$inc": {"views": 1}})
def ask(request, *args, **kwargs): if request.method == 'GET': form = AskForm() url_ask = reverse(ask) return render(request, 'qa/ask_question.html', { 'form': form, 'url': url_ask, 'user': request.user, }) if request.method == 'POST' and request.user.is_authenticated(): form = AskForm(request.POST) if form.is_valid(): que = Question() save_id = que.save_data(form, request.user.id) return HttpResponseRedirect( reverse(question_details, args=(save_id, ))) else: return HttpResponseRedirect(reverse(qa_login, ))
def form_valid(self, form): action = self.request.POST.get('action') if action == 'SAVE': return super().form_valid(form) elif action == 'PREVIEW': preview = Question(question=form.cleaned_data["question"], title=form.cleaned_data["title"]) ctx = self.get_context_data(preview=preview) return self.render_to_response(context=ctx) return HttpResponseBadRequest()
def save(self): question = Question(**self.cleaned_data) question.added_at = datetime.now() question.rating = 0 question.author = self._user question.save() return question
def save(self): question = Question(**self.cleaned_data) user,_ = User.objects.get_or_create(username='******',password='******') question.author=user question.added_at=datetime.today() question.save() return question
def test_question(self): from qa.models import Question try: title = Question._meta.get_field('title') except FieldDoesNotExist: assert False, "title field does not exist in Question model" assert isinstance(title, CharField), "title field is not CharField" try: text = Question._meta.get_field('text') except FieldDoesNotExist: assert False, "text field does not exist in Question model" assert isinstance(text, TextField), "text field is not TextField" try: added_at = Question._meta.get_field('added_at') except FieldDoesNotExist: assert False, "added_at field does not exist in Question model" assert isinstance(text, DateField) or isinstance(added_at, DateField), "added_at field is not DateTimeField" try: rating = Question._meta.get_field('rating') except FieldDoesNotExist: assert False, "rating field does not exist in Question model" assert isinstance(rating, IntegerField), "text field is not IntegerField" try: author = Question._meta.get_field('author') except FieldDoesNotExist: assert False, "author field does not exist in Question model" assert isinstance(author, ForeignKey), "author field is not ForeignKey" assert author.related.parent_model == User, "author field does not refer User model" try: likes = Question._meta.get_field('likes') except FieldDoesNotExist: assert False, "likes field does not exist in Question model" assert isinstance(likes, ManyToManyField), "likes field is not ManyToManyField" assert likes.related.parent_model == User, "likes field does not refer User model" user, _ = User.objects.get_or_create(username='******', password='******') try: question = Question(title='qwe', text='qwe', author=user) question.save() except: assert False, "Failed to create question model, check db connection"
def create(self, validated_data): comment = Comment() request = self.context.get("request") token = request.headers.get("Authorization").split()[1] payload = jwt_decode_handler(token) user_id = payload.get("user_id") comment.set_user_id(user_id) comment.set_message(validated_data.get("message")) data = { "user_id": ObjectId(user_id), "message": comment.get_message(), "date_created": comment.get_date_created(), } c_id = comment.save(data) comment.set_id(c_id) # Add comment's id to question comment list if self.context.get("question_id"): question = Question() qs = question.collection.find( {"_id": ObjectId(self.context.get("question_id"))}) if qs.count() == 1: question_obj = qs.next() comments_list = question_obj.get("comments") comments_list.append(str(comment.get_id())) data = {"comments": comments_list} question.update({"_id": question_obj.get("_id")}, data) # Add comment's id to answer comment list elif self.context.get("answer_id"): answer = Answer() qs = answer.collection.find( {"_id": ObjectId(self.context.get("answer_id"))}) if qs.count() == 1: answer_obj = qs.next() comments_list = answer_obj.get("comments") comments_list.append(str(comment.get_id())) data = {"comments": comments_list} answer.update({"_id": answer_obj.get("_id")}, data) return comment
def save(self): question = Question(**self.cleaned_data) #t7 user,_ = User.objects.get_or_create(username='******',password='******') #t7 question.author=user question.author_id = self._user.id question.added_at = datetime.today() if self._user.id is None: user, _ = User.objects.get_or_create(username='******', password='******') question.author = user else: pass question.save() return question
def test_question(self): user, _ = User.objects.get_or_create(username='******', password='******') try: question = Question(title='qwe', text='qwe', author=user) question.save() except: assert False, "Failed to create question model, check db connection" try: answer = Answer(text='qwe', question=question, author=user) question.save() answer.save() except: assert False, "Failed to create answer model, check db connection"
def ask(request): print(request.user) if request.method == "POST": q = QueryDict(request.POST.urlencode(), mutable=True) q['author'] = str(request.user.id) print(q) form = AskForm(q) print(form['author'].value()) if form.is_valid(): print("Valid ask") quest = form.save() return HttpResponseRedirect(quest.get_url()) else: user = request.user if not user.is_active: user = User.objects.get(pk=1) quest = Question(author=user) form = AskForm(instance=quest) return render(request, 'ask.html', {'form': form})
def answer_st(request, pk): if request.method == 'POST': form = AnswerForm(request.POST) if request.user.is_authenticated(): pass else: if form.is_valid(): post = form.save(commit=False) post.author = User(id=1) #q = Question.objects.filter(id=2) post.added_at = timezone.now() post.question = Question(id=pk) post.save() return HttpResponseRedirect('/answers/') else: form = AskForm() return render(request, 'qa/answer.html', {'form': form})
def save(self): self.cleaned_data['author_id'] = 1 askquestion = Question(**self.cleaned_data) askquestion.save() return askquestion
def save(self): question = Question(**self.cleaned_data) question.author_id = self.user.id question.save() return question
def save(self): q = Question(**self.cleaned_data) q.author_id = self._user.id q.save() return q
def save(self): self.cleaned_data['author'] = self.user question = Question(**self.cleaned_data) question.save() #question = Question.objects.create(text=self.cleaned_data['text'], title=self.cleaned_data['title'], author=self.user) return question
def ask_question(request): if not request.user.is_authenticated(): return redirect('/') else: hut_slug = request.POST['hut'] hut = Course.objects.get(slug=hut_slug) title = request.POST['title'] if len(title) == 0: return ask(request, error='You need to enter a title.', hut_slug=hut_slug) content = request.POST['content'] if len(content) == 0: return ask(request, error='You need to enter some content to your question.', title=title, hut_slug=hut_slug) tags = request.POST['tags'].strip().replace(',', '').replace('#', '').split(' ') if len(tags) == 1 and len(tags[0]) == 0: return ask(request, error='You need to enter some tags.', title=title, content=content, hut_slug=hut_slug) question = Question(title=title, content=content, author=request.user, course=hut) question.save() question.add_tag(hut.slug) question.add_tag(State.CURRENT_QUARTER) question.add_follower(request.user) for tag in tags: question.add_tag(tag) if hut.has_approved(request.user): question.approved = True question.save() message_subscribers(hut, question, request.user) return redirect('/question/%d' % question.id) return redirect('/?msg=moderation')
def save(self): self.cleaned_data['author_id'] = 1 post = Question(**self.cleaned_data) post.save() return post
def save(self): question = Question(**self.cleaned_data) question.author_id = 1 question.save() return question
def save(self): ask = Question(**self.cleaned_data) ask.author_id = self._user.id ask.save() return ask
def save(self): ask = Question(**self.cleaned_data) ask.save() return ask
def save(self): self.cleaned_data['author'] = self._user question = Question(**self.cleaned_data) question.save() return question
def save(self, user): q = Question(author=user, **self.cleaned_data) q.save() return q
def save(self): question = Question(**self.cleaned_data) question.author = self.instance.author question.save() return question
["sixth","what is the time now??", datetime.now(),17,56,User.objects.get(username="******")], ["seventh","how much is the fish",datetime.now(),12,8,User.objects.get(username="******")], ["eghth","WTF 0_o ???", datetime.now(),6,14,User.objects.get(username="******")], ["ninegth","what is the time now??", datetime.now(),10,20,User.objects.get(username="******")], ["tenth","how much is the fish",datetime.now(),0,0,User.objects.get(username="******")], ["eleven","WTF 0_o ???", datetime.now(),14,56,User.objects.get(username="******")], ["tvelve","what is the time now??", datetime.now(),22,34,User.objects.get(username="******")], ["forteen","how much is the fish",datetime.now(),24,56,User.objects.get(username="******")], ["sixteenth","WTF 0_o ???", datetime.now(),23,32,User.objects.get(username="******")], ["eigtheenth","what is the time now??", datetime.now(),34,17,User.objects.get(username="******")], ] for question in questions: title,text,added_at,rating,likes,author = question question=Question(title=title,text=text,added_at=added_at,rating=rating,likes=likes,author=author) question.save() answers = [ ["dorogo",datetime.now(),Question.objects.get(title="first"),User.objects.get(username="******")], ["togo!togo",datetime.now(),Question.objects.get(title="second"),User.objects.get(username="******")], ["13:00 o clock!!", datetime.now(),Question.objects.get(title="second"),User.objects.get(username="******")], ] for answer in answers: text,added_at,question,author = answer answer=Answer(text=text,added_at=added_at,question=question,author=author) answer.save()
from django.db.models.fields.files import ImageField from django.db.models.fields.related import ForeignKey, ManyToManyField from django.utils import timezone import django if hasattr(django, 'setup'): django.setup() from django.contrib.auth.models import User from qa.models import Question user, _ = User.objects.get_or_create( username='******', defaults={'password':'******', 'last_login': timezone.now()}) #try: question = Question(title='qwe', text='qwe', author=user) question.save() #except: # assert False, "Failed to create question model, check db connection" class TestQuestionManager(unittest.TestCase): def test_question_manager(self): from qa.models import Question from qa.models import QuestionManager mgr = Question.objects assert isinstance(mgr, QuestionManager), "Question.objects is not an QuestionManager" assert hasattr(mgr, 'new'), "QuestionManager has no 'new' queryset method" assert hasattr(mgr, 'popular'), "QuestionManager has no 'popular' queryset method"
def save(self): user, _ = User.objects.get_or_create(username='******', defaults={'password': '******'}) q = Question(title=self.cleaned_data['title'], text=self.cleaned_data['text'], author=user) q.save() return q
def save(self): question = Question(**self.cleaned_data) question.save() return question
def save(self): question = Question(text=self.cleaned_data['text'], title=self.cleaned_data['title'], author=self._user) question.save() return question
def save(self): question = Question(**self.cleaned_data) question.author = self._user question.save() return question
def save(self): self.cleaned_data['author'] = self.user question = Question(**self.cleaned_data) question.save() return question
def save(self,user): # self.cleaned_data['author_id'] = 1 post = Question(**self.cleaned_data) post.author=user post.save() return post
def post(self, request): if not request.user.is_authenticated(): return HttpResponse(json.dumps({ "status": "fail", "msg": "用户未登录" }), content_type='application/json') content = request.POST.get('content', '') obj_type = request.POST.get('obj_type', '') obj_id = request.POST.get('obj_id', '') if int(obj_id) > 0 and content: question = Question() question.content = content question.user = request.user question.question_type = '3' question.question_source = '2' question.file_linenum = 9999 if obj_type == 'file': file = File.objects.get(id=obj_id) question.content_object = file question.file_id = file.id elif obj_type == 'function': function = Function.objects.get(id=obj_id) question.content_object = function question.function_id = function.id elif obj_type == 'line': line = Line.objects.get(id=obj_id) question.content_object = line question.file_linenum = line.file_linenum question.file_id = line.file_id if line.function_linenum: question.function_linenum = line.function_linenum question.function_id = line.function_id question.function_content = content question.save() return HttpResponse('{"status":"success","msg":"提问成功"}', content_type='application/json') else: return HttpResponse('{"status":"fail","msg":"提问失败"}', content_type='application/json')