Django 为每个"user"分配"score"



作为一名初学者,我正在尝试用django练习我的技能,我与用户和问答一起构建了这个平台。如果登录,用户可以进行测验。我的目标是在"用户档案"页面上打印他/她参加的测试的分数。你对我如何将分数链接到用户有什么建议吗?或者你有什么资源可以关注吗?

账户/表格.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/uls.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/uls.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'

问答/管理员.py

from django.contrib import admin
from .models import Questions
# Register your models here.
admin.site.register(Questions)

测验/模型.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

问答/uls.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'),
]

测验/视图.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})



#
#
#
#
#
#
#

也许使用一个模型来存储用户、问题和分数是一个好的开始。

测验/模型.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()

最新更新