Django присваивать "очки" каждому "пользователю" - PullRequest
0 голосов
/ 17 апреля 2020

Я пытаюсь отработать свои навыки с django как новичок, я создал эту платформу с пользователями и викторинами. Если вы вошли в систему, пользователь может пройти тест. Моя цель здесь - напечатать на странице «Профиль пользователя» результаты тестов, которые он / она прошли. Есть ли у вас какие-либо предложения о том, как я могу связать счет с пользователем? Или у вас есть какой-либо ресурс для подписки?

account / forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class FormRegistrazione(UserCreationForm):
    email = forms.CharField(max_length=30, required=True, widget=forms.EmailInput())

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

account / urls.py

from django.urls import path
from .views import registrazioneView

urlpatterns = [
    path('registrazione/', registrazioneView, name='registration_view')
]

account / views.py

from django.shortcuts import render, HttpResponseRedirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from accounts.forms import FormRegistrazione

# Create your views here.

def registrazioneView(request):
    if request.method == "POST":
        form = FormRegistrazione(request.POST)
        if form.is_valid():
            username = form.cleaned_data["username"]
            email = form.cleaned_data["email"]
            password = form.cleaned_data["password1"]
            User.objects.create_user(username=username, password=password, email=email)
            user = authenticate(username=username, password=password)
            login(request, user)
            return HttpResponseRedirect("/")
    else:
        form = FormRegistrazione()
    context = {"form": form}
    return render(request, 'accounts/registrazione.html', context)

core / urls.py

from django.urls import path
from . import views


urlpatterns = [
    path("", views.homepage, name='homepage'),
    path("users/", views.UserList.as_view(), name='user_list'),
    path("user/<username>/", views.userProfileView, name='user_profile'),

]

core / views.py

from django.shortcuts import render, get_object_or_404
from django.contrib.auth.models import User

from django.views.generic.list import ListView

# Create your views here.
def homepage(request):
    return render(request, 'core/homepage.html')

def userProfileView(request, username):
    user= get_object_or_404(User, username=username)
    context = {'user' : user}
    return render(request, 'core/user_profile.html' , context)

class UserList(ListView):
    model = User
    template_name = 'core/users.html'

quiz / admin.py

from django.contrib import admin
from .models import Questions

# Register your models here.
admin.site.register(Questions)

quiz /models.py

from django.db import models

# Create your models here.

class Questions(models.Model):
    CAT_CHOICES = (
    ('datascience', 'DataScience'),
    ('productowner', 'ProductOwner'),
    ('businessanalyst', 'BusinessAnalyst'),
    #('sports','Sports'),
    #('movies','Movies'),
    #('maths','Maths'),
    #('generalknowledge','GeneralKnowledge'),


)
    question = models.CharField(max_length = 250)
    optiona = models.CharField(max_length = 100)
    optionb = models.CharField(max_length = 100)
    optionc = models.CharField(max_length = 100)
    optiond = models.CharField(max_length = 100)
    answer = models.CharField(max_length = 100)
    category = models.CharField(max_length=20, choices = CAT_CHOICES)

    class Meta:
        ordering = ('-category',)

    def __str__(self):
        return self.question

викторина / urls.py

from django.urls import path, re_path, include
from . import views

# urlpatterns = [
#                 path("quiz/", views.quiz, name='quiz'),
#                 path("questions/<choice>/", views.questions, name='questions'),
#                 path("result/", views.result, name='result'),
#
# ]

urlpatterns = [
    re_path(r'^quiz', views.quiz, name = 'quiz'),
    re_path(r'^result', views.result, name = 'result'),
    re_path(r'^(?P<choice>[\w]+)', views.questions, name = 'questions'),
]

викторина / views.py

from django.shortcuts import render

# Create your views here.
from django.shortcuts import render
from .models import Questions

# Create your views here.
def quiz(request):
    choices = Questions.CAT_CHOICES
    print(choices)
    return render(request,
        'quiz/quiz.html',
        {'choices':choices})

def questions(request , choice):
    print(choice)
    ques = Questions.objects.filter(category__exact = choice)
    return render(request,
        'quiz/questions.html',
        {'ques':ques})

def result(request):
    print("result page")
    if request.method == 'POST':
        data = request.POST
        datas = dict(data)
        qid = []
        qans = []
        ans = []
        score = 0
        for key in datas:
            try:
                qid.append(int(key))
                qans.append(datas[key][0])
            except:
                print("Csrf")
        for q in qid:
            ans.append((Questions.objects.get(id = q)).answer)
        total = len(ans)
        for i in range(total):
            if ans[i] == qans[i]:
                score += 1
        # print(qid)
        # print(qans)
        # print(ans)
        print(score)
        eff = (score/total)*100
    return render(request,
        'quiz/result.html',
        {'score':score,
        'eff':eff,
        'total':total})






#
#
#
#
#
#
#

1 Ответ

0 голосов
/ 17 апреля 2020

Возможно, используйте модель для хранения пользователей, вопросов и оценок, это хорошее начало.

quiz / models.py

class Quiz(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="quizs", on_delete=models.CASCADE)
    question = models.ManyToManyField(Questions, related_name="quizs")
    score = models.IntegerField()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...