Spaces:
Running
Running
| from django.shortcuts import render,get_object_or_404 | |
| from django.http import HttpResponse,Http404,HttpResponseRedirect,JsonResponse | |
| from django.contrib.auth import login as auth_login,logout as auth_logout | |
| from django.contrib.auth import get_user_model | |
| from django.contrib.auth.decorators import login_required | |
| from django.urls import reverse | |
| import json | |
| from .models import Question,Choice,Vote,ThemeColor | |
| from .forms import UserSignupForm,UserLoginForm | |
| User = get_user_model() # user model | |
| # Create your views here. | |
| login_url="/login/" | |
| def index(request): | |
| latest_questions_list = Question.objects.order_by("-pub_date")[:5] | |
| for q in latest_questions_list: | |
| q.has_voted=q.has_user_voted(request.user) | |
| # print(latest_questions_list[0].has_voted) | |
| context={"latest_questions_list":latest_questions_list, | |
| } | |
| return render(request,"polls/index.html",context) | |
| def vote(request): | |
| if request.method=='POST': | |
| json_data=json.loads(request.body) | |
| print(json_data) | |
| choice=get_object_or_404(Choice,pk=json_data['choice_id']) | |
| # check if already has voted on this question | |
| old_vote_on_same_question=Vote.objects.filter(user=request.user,choice__question=choice.question) | |
| if len(old_vote_on_same_question)>0: | |
| return JsonResponse({ | |
| "message":"error", | |
| 'error_message':"you have already voted !" | |
| }) | |
| vote=Vote.objects.create(choice=choice,user=request.user) | |
| vote.save() | |
| # get percentage of each choice for showing result | |
| vote_percent_dict={c.pk:c.vote_percent for c in choice.question.choice_set.all()} | |
| # print(vote_percent_dict) | |
| return JsonResponse({ | |
| "message":"success", | |
| "vote_percent_dict" :vote_percent_dict, | |
| }) | |
| def signup(request): | |
| form=UserSignupForm(request.POST or None) | |
| context={} | |
| if form.is_valid(): | |
| form.save() | |
| # successfully login the user | |
| auth_login(request,User.objects.get(email=form.cleaned_data['email'])) | |
| next_url=request.POST['next'] if request.POST['next']!='' else reverse("polls:index") | |
| return HttpResponseRedirect(next_url) | |
| if form.is_bound: | |
| data={} | |
| fields=['username','email'] | |
| for field in fields: | |
| if form.errors.get(field) is None: | |
| data[field]=form.data[field] | |
| context['errors']=form.errors | |
| context['data']=data | |
| print(data) | |
| # print(form.errors.as_json()) | |
| return render(request,"polls/signup.html",context) | |
| def login(request): | |
| form = UserLoginForm(request.POST or None) | |
| context={} | |
| if form.is_valid(): | |
| # print(form.cleaned_data) | |
| email=form.cleaned_data.get('email') | |
| password=form.cleaned_data.get('password') | |
| try: | |
| user = User.objects.get(email=email) | |
| # print(user) | |
| if user.check_password(password): | |
| # successfully login the user | |
| auth_login(request,user) | |
| next_url=request.POST['next'] if request.POST['next']!='' else reverse("polls:index") | |
| return HttpResponseRedirect(next_url) | |
| else: | |
| # incorrect password | |
| form.add_error('password','incorrect password.') | |
| except User.DoesNotExist: | |
| # add error no such user | |
| form.add_error('email','No Account associated with this email.') | |
| if form.is_bound: | |
| data={} | |
| fields=['email'] | |
| for field in fields: | |
| if form.errors.get(field) is None: | |
| data[field]=form.data[field] | |
| context={'errors':form.errors, | |
| 'data':data} | |
| # print(context) | |
| return render(request,"polls/login.html",context) | |
| def create(request): | |
| if request.method=="GET": | |
| context={} | |
| if "q" in request.GET: | |
| context['q']=get_object_or_404(Question,pk=request.GET['q']) | |
| # "No such question exists" | |
| if context['q'].author!=request.user: | |
| # they don't have access to this question | |
| raise Http404("this question does't belongs to you.") | |
| # get themes | |
| themes=ThemeColor.objects.all() | |
| context["themes"]=themes | |
| return render(request,'polls/create.html',context) | |
| json_data=json.loads(request.body) | |
| print(json_data) | |
| if "theme_color" in json_data: | |
| theme_color=ThemeColor.objects.get(pk=json_data['theme_color']) | |
| else: | |
| theme_color=None | |
| if "id" in json_data: | |
| question=get_object_or_404(Question,pk=json_data['id']) | |
| question.choice_set.all().delete() | |
| else: | |
| question=Question.objects.create(author=request.user,question_text=json_data['question_text']) | |
| question.author=request.user | |
| question.question_text=json_data['question_text'] | |
| question.theme_color=theme_color | |
| question.save() | |
| for choice_text in json_data['choice_text_list']: | |
| choice=Choice.objects.create(question=question,choice_text=choice_text) | |
| choice.save() | |
| return JsonResponse({ | |
| "redirect":reverse("polls:index") | |
| }) | |
| def your_polls(request): | |
| latest_questions_list = Question.objects.filter(author=request.user).order_by("-pub_date")[:5] | |
| for q in latest_questions_list: | |
| q.has_voted=q.has_user_voted(request.user) | |
| context={"latest_questions_list":latest_questions_list, | |
| "canDelete":True} | |
| return render(request,'polls/your_polls.html',context) | |
| def your_votes(request): | |
| user_voted_questions = Vote.objects.filter(user=request.user) | |
| user_voted_questions = Choice.objects.filter(vote_set__in=user_voted_questions) | |
| user_voted_questions = Question.objects.filter(choice_set__in=user_voted_questions) | |
| # user_voted_questions = Question.objects.all() | |
| print(user_voted_questions) | |
| # print(user_voted_questions[0].choice_set) | |
| for q in user_voted_questions: | |
| q.has_voted=True | |
| context={"latest_questions_list":user_voted_questions} | |
| return render(request,'polls/your_votes.html',context) | |
| def detail(request,question_id): | |
| try: | |
| question=Question.objects.get(pk=question_id) | |
| except Question.DoesNotExist: | |
| raise Http404("Question Does Not Exists") | |
| # question=get_object_or_404(Question,pk=question_id) | |
| question.has_voted=question.has_user_voted(request.user) | |
| return render(request,"polls/detail.html",{"latest_questions_list":[question]}) | |
| def logout(request): | |
| auth_logout(request) | |
| return HttpResponseRedirect(reverse('polls:login')) | |
| def delete_view(request): | |
| if request.method=="POST": | |
| json_data=json.loads(request.body) | |
| question=get_object_or_404(Question,pk=json_data['question_id']) | |
| question.delete() | |
| return JsonResponse({"message":"success"}) | |
| def settings(request): | |
| raise Http404() |