def post(self, request, *args, **kwargs): new_question = Question() course = get_object_or_404(Course, slug=self.kwargs['course_slug']) new_question.course = course new_question.user = request.user form = QuestionForm(instance=new_question, **self.get_form_kwargs()) if form.is_valid(): form.save() self.success_url = reverse_lazy('forum_question', kwargs={'slug': new_question.slug}) return self.form_valid(form) else: return self.form_invalid(form)
def test_question_form(user): from forum.forms import QuestionForm from forum.models import Question instance = Question() instance.course = mommy.make('Course', slug='dbsql') instance.user = user data = { 'title': 'Test Title', 'text': 'asljf asdfhuas dfasdflashfdlusafdlsafdlsa filasdflisalfdiayslfdnsalfdyaslifd', } form = QuestionForm(instance=instance, data=data) assert form.is_valid() is True, form.errors form.save() assert Question.objects.filter(slug='test-title').exists() data = { 'title': '', 'text': 'asljf asdfhuas dfasdflashfdlusafdlsafdlsa filasdflisalfdiayslfdnsalfdyaslifd', } form = QuestionForm(data=data) assert form.is_valid() is False data = { 'title': 'Test Title', 'text': '', } form = QuestionForm(data=data) assert form.is_valid() is False
def submit_question(request): if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): question = form.save(commit=False) question.user = request.user question.save() for tag in form.cleaned_data['tags']: question.tags.add(tag) question.save() return HttpResponseRedirect(reverse('forum.views.view_question', kwargs={'slug':question.slug})) else: form = QuestionForm() return render(request, 'submit_question.html', { 'form': form, })
def ask(request): if request.method == 'POST': question_form = QuestionForm(request.POST) if question_form.is_valid(): question = question_form.save(commit=False) question.published = 'P' question.user = request.user question.save() question_form.save_m2m() question.tags.add( *_get_or_create_tags(question_form.cleaned_data['tags'])) profile = Profile.objects.get(user=request.user) profile.change_star(settings.STAR_RULES['ASKING_QUESTION']) return HttpResponseRedirect('/') else: question_form = QuestionForm() return render(request, 'forum/ask.html', {'question_form': question_form})
def edit_question(request, question_id): try: q = Question.objects.get(id=question_id) except Question.DoesNotExist: raise Http404 if request.method == 'POST': question_form = QuestionForm(request.POST, instance=q) if question_form.is_valid(): question = question_form.save() question.tags.all().delete() question.tags.add( *_get_or_create_tags(question_form.cleaned_data['tags'])) return HttpResponseRedirect( reverse('question_page', kwargs={"question_id": q.id})) else: question_form = QuestionForm(instance=q, initial={ 'tags': ' '.join(q.tags.all().values_list( 'name', flat=True)) }) return render(request, 'forum/ask.html', {'question_form': question_form})