def edit_choice_api(request, question_id): if request.method == 'POST': choice_list = json.loads(request.body) error_message = None # Algorithm: Delete choices database_choice_list_ids = [ i.id for i in Question.objects.get(pk=question_id).choice_set.all() ] choice_list_ids = list() for i in choice_list: try: choice_list_ids.append(i['id']) except KeyError: pass for i in database_choice_list_ids: if i not in choice_list_ids: Choice.objects.get(pk=i).delete() # Algorithm: Validations for i in choice_list: print(type(i['value'])) if i['text'] == '' or i['value'] == '': error_message = 'Fields can\'t be left blank.' break error_message = None # Algorithm: Save choices if not error_message: for i in choice_list: try: # Case: Choice already exists. Choice.objects.filter(pk=i['id']).update(text=i['text'], value=i['value']) except KeyError: # Case: Choice doesn't exist. form = ChoiceForm({ 'text': i['text'], 'value': i['value'], 'question': question_id, }) if form.is_valid(): form.save() else: error_message = 'Fields can\'t be left blank.' break if not error_message: return JsonResponse({'message': 'success'}, status=200) return JsonResponse({'message': error_message}, status=400) return JsonResponse({'message': 'This API doesn\'t accept GET requests.'}, status=405)
def updatech(request, id): polls = Choice.objects.get(id=id) print(polls) form = ChoiceForm(request.POST, instance = polls) print(form) if form.is_valid(): print("valid") form.save() return redirect('/polls/viewch') return render(request, 'editch.html', {'form': form})
def add_choice(request): if request.method == 'POST': form = ChoiceForm(request.POST) if form.is_valid(): form.save(commit=True) return HttpResponseRedirect('/polls/') #return IndexView(request) else: print form.errors else: form = ChoiceForm() return render(request, 'polls/add_choice.html',{'form': form})
def get_choice(request): form = ChoiceForm(request.POST or None) if request.method == "POST": if form.is_valid(): choice_text = form.cleaned_data["choice_text"] votes = form.cleaned_data["votes"] question = form.cleaned_data["question"] Choice.objects.create(choice_text=choice_text, votes=votes, question=question) return HttpResponse("IT WORKED") return render(request, template_name="my_name.html", context={"form": form})
def new_choice(request): """vista que crea un formulario apartir del modelo.... donde toca seleccionar en que question agregar el choice pero no es la mejor manera para una vista publica """ if request.method == 'POST': formulario = ChoiceForm(request.POST) if formulario.is_valid(): formulario.save() return HttpResponseRedirect('/polls/') else: formulario = ChoiceForm() return render_to_response('choiceform.html', {'formulario':formulario}, context_instance=RequestContext(request))
def createChoice(request, poll_id): poll = get_object_or_404(Poll, pk=poll_id) form = ChoiceForm(request.POST or None) if not form.is_valid(): context = {} poll = get_object_or_404(Poll, pk=poll_id) context['form'] = form context['poll'] = poll return render(request, 'polls/detail.html', context) else: obj = form.save(commit=False) obj.poll = poll obj.votes = 0 obj.save() return HttpResponseRedirect('/polls/'+poll_id+'/')
def add_course(request): if request.user.first_name != '': user_first_name = request.user.first_name else: user_first_name = request.user.username context = RequestContext(request) message = "" if request.method == 'POST': form = ChoiceForm(data=request.POST) if form.is_valid(): if not Choice.objects.filter(new_course=request.POST['new_course']).exists(): form.save() return index(request) else: message = "Sorry, this course already exists in the list." else: print form.errors else: form = ChoiceForm() return render_to_response('polls/add_course.html', {'form': form, 'user_first_name': user_first_name, 'message': message, }, context)
def create_choice(request): q = Question.objects.all() if request.method == 'POST': form = ChoiceForm(request.POST) if form.is_valid(): form.save() return redirect('polls:index') else: form = ChoiceForm() return render(request, 'polls/create_choice.html', {'form': form, 'q': q})
def registerC(request, question_id): question = get_object_or_404(Question, pk=question_id) if 'username' not in request.session: return render(request, 'polls/error.html', {'error': '로그인 후 접근할 수 있는 페이지입니다.'}) if question.customuser.id == request.session['username']: if request.method == "GET": #get_object_or_404(모델 클래스명, pk=id 값을 가진 변수) #입력한 모델클래스에서 객체를 찾아서 없는 경우 404Error 띄어준다 question = get_object_or_404(Question, pk=question_id) obj = ChoiceForm() return render(request, 'polls/registerC.html/', { 'form': obj, 'question': question }) else: obj = ChoiceForm(request.POST) if obj.is_valid(): choice = obj.save(commit=False) choice.question = question #question 객체를 넘겨줘야한다 choice.save() return HttpResponseRedirect( reverse('polls:detail', args=(question_id, ))) else: return render(request, 'polls/registerC.html', { 'form': obj, 'error_message': "비정상적인 값입니다." }) else: #현재 글과 로그인된 유저의 이름이 다름 return render(request, 'polls/error.html', {'error': '본인이 작성한 글이 아닙니다.'})
def edit_choice(request, choice_id): choice = get_object_or_404(Choice, id=choice_id) poll = get_object_or_404(Poll, id=choice.poll.id) if request.user != poll.owner: return redirect('/') if request.method == 'POST': form = ChoiceForm(request.POST, instance=choice) if form.is_valid(): choice.save() messages.success( request, "Choice edited successfully!!", extra_tags="alert alert-warning alert-dismissible fade show") return redirect('polls:list') else: form = ChoiceForm(instance=choice) return render(request, 'polls/add_choice.html', { 'form': form, 'poll': poll, 'edit_mode': True, 'choice': choice })
def add_choice(request, poll_id): poll = Poll.objects.get(pk=poll_id) if request.user.id != poll.create_by.id: return redirect('/') if request.method == "POST": form = ChoiceForm(request.POST, request.FILES) if form.is_valid(): new_choice = form.save(commit=False) new_choice.poll_id_id = poll_id new_choice.save() return redirect('my_poll') else: form = ChoiceForm() return render(request,'polls/add_choice.html', {'form':form})
def pollch(request): if request.method == "POST": print("POST4") form = ChoiceForm(request.POST) #print(form.cleaned_data['question_text']) print("POST3") if form.is_valid(): print("POST1") try: form.save() print("POST2") return redirect('/polls/viewch') except: pass else: print("GET") form = ChoiceForm() return render(request,'indexch.html',{'form':form})
def index(request): latest_poll_list = Poll.objects.order_by('-pub_date')[:5] pollform = PollForm() choiceform = ChoiceForm() if request.method == 'POST': pollform = PollForm(request.POST, request.FILES) choiceform = ChoiceForm(request.POST) if pollform.is_valid(): pollform.comments = pollform.cleaned_data['comments'] pollform.save() else: pollform = PollForm() if choiceform.is_valid(): choiceform.save() else: choiceform = ChoiceForm() context = {'latest_poll_list': latest_poll_list, 'pollform': pollform, 'choiceform': choiceform} return render(request, 'polls/index.html', context)
def registerC(request,question_id): if not 'username' in request.session: return render(request, 'polls/error.html',{'error':'로그인 후 접근할 수 있는 페이지 입니다.'}) question = get_object_or_404(Question,pk=question_id) if question.customuser.id == request.session['username']: if request.method =="GET": obj = ChoiceForm() return render(request, 'polls/registerC.html', {'form' : obj }, {'question' : question}) else: obj = ChoiceForm(request.POST) if obj.is_valid(): choice = obj.save(commit=False) choice.question = question choice.save() return HttpResponseRedirect(reverse('polls:detail', args=(question_id,))) else: return render(request, 'polls/registerC.html', {'form' : obj, 'error_message' : "비정상적인 값입니다."}) else: return render(request, 'polls/error.html', {'error': '본인이 작성한 글이 아닙니다.'})
def registerC(request, question_id): if 'username' not in request.session: return render(request, 'polls/error.html', {'error': '로그인 후 접근할 수 있는 페이지 입니다.'}) question = get_object_or_404(Question, pk=question_id) if question.customuser.id == request.session['username']: if request.method == "GET": #해당 뷰를 GET 방식으로 요청시(페이지 접근) #QuestionForm 객체를 생성 - HTML에서 form 태그 컨텐츠안에 넣으면 됨 #get_object_or_404(모델클래스명, pk=id값을 가진 변수) #from django.shortcuts import get_object_or_404 #입력한 모델클래스에서 객체를 찾아서 없는경우 404Error 띄워줌 obj = ChoiceForm() return render(request, 'polls/registerC.html', { 'form': obj, 'question': question }) else: #해당 뷰를 POST방식으로 요청시 #request.POST.get("") form내에 있는 특정 변수값을 가져올때 #request.POST form내에 있는 모든 값을 사용 #POST방식으로 온 데이터를 QuestionForm에 삽입 obj = ChoiceForm(request.POST) #obj.is_valid() : 사용자가 <form>에 있는 양식을 잘 작성했는지 확인(True,False) if obj.is_valid(): #값이 유효한가? #obj.save() : QuestionForm을 Question 객체로 변환 후,데이터베이스에 저장 #obj.save(commit = False) : QuestionForm을 Question객체로 변환 choice = obj.save(commit=False) choice.question = question #question객체를 넘겨줘야함 choice.save() return HttpResponseRedirect( reverse('polls:detail', args=(question_id, ))) else: #값이 유효하지 않을때 처리 return render(request, 'polls/registerC.html', { 'form': obj, 'error_message': "비정상적인 값입니다." }) else: #현재 글과 로그인된 유저의 이름이 다름 return render(request, 'polls/error.html', {'error': '본인이 작성한 글이 아닙니다'})
def add_choice(request, poll_id): poll = get_object_or_404(Poll, id=poll_id) if request.user != poll.owner: return redirect('/') if request.method == 'POST': form = ChoiceForm(request.POST) if form.is_valid(): choice = form.save(commit=False) choice.poll = poll choice.save() messages.success( request, "Choice added successfully!!", extra_tags="alert alert-warning alert-dismissible fade show") return redirect('polls:list') else: form = ChoiceForm() return render(request, 'polls/add_choice.html', { 'form': form, 'poll': poll })