django-flashdeck 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. django_flashdeck-0.1.0.dist-info/METADATA +215 -0
  2. django_flashdeck-0.1.0.dist-info/RECORD +53 -0
  3. django_flashdeck-0.1.0.dist-info/WHEEL +4 -0
  4. django_flashdeck-0.1.0.dist-info/licenses/LICENSE +28 -0
  5. flashdeck/__init__.py +1 -0
  6. flashdeck/admin.py +68 -0
  7. flashdeck/apps.py +8 -0
  8. flashdeck/bundles.py +346 -0
  9. flashdeck/conf.py +19 -0
  10. flashdeck/images.py +85 -0
  11. flashdeck/management/__init__.py +0 -0
  12. flashdeck/management/commands/__init__.py +0 -0
  13. flashdeck/management/commands/flashdeck_export.py +23 -0
  14. flashdeck/management/commands/flashdeck_import.py +29 -0
  15. flashdeck/manifest.py +33 -0
  16. flashdeck/marking.py +107 -0
  17. flashdeck/migrations/0001_initial.py +146 -0
  18. flashdeck/migrations/0002_card_options.py +44 -0
  19. flashdeck/migrations/0003_reference.py +28 -0
  20. flashdeck/migrations/__init__.py +0 -0
  21. flashdeck/models.py +325 -0
  22. flashdeck/practice.py +232 -0
  23. flashdeck/reference.py +108 -0
  24. flashdeck/scheduling.py +75 -0
  25. flashdeck/static/flashdeck/flashdeck.css +241 -0
  26. flashdeck/static/flashdeck/flashdeck.js +137 -0
  27. flashdeck/stats.py +248 -0
  28. flashdeck/templates/flashdeck/_account.html +1 -0
  29. flashdeck/templates/flashdeck/_assets.html +2 -0
  30. flashdeck/templates/flashdeck/_crumbs.html +1 -0
  31. flashdeck/templates/flashdeck/_crumbs_root.html +1 -0
  32. flashdeck/templates/flashdeck/_forms.html +3 -0
  33. flashdeck/templates/flashdeck/_prompt.html +5 -0
  34. flashdeck/templates/flashdeck/_reference_dialog.html +8 -0
  35. flashdeck/templates/flashdeck/_search.html +5 -0
  36. flashdeck/templates/flashdeck/admin/bundles.html +24 -0
  37. flashdeck/templates/flashdeck/fragment.html +1 -0
  38. flashdeck/templates/flashdeck/index.html +29 -0
  39. flashdeck/templates/flashdeck/nothing_due.html +21 -0
  40. flashdeck/templates/flashdeck/page.html +23 -0
  41. flashdeck/templates/flashdeck/progress.html +80 -0
  42. flashdeck/templates/flashdeck/question.html +46 -0
  43. flashdeck/templates/flashdeck/reference_deck.html +28 -0
  44. flashdeck/templates/flashdeck/reference_item.html +18 -0
  45. flashdeck/templates/flashdeck/reference_subject.html +19 -0
  46. flashdeck/templates/flashdeck/result.html +56 -0
  47. flashdeck/templates/flashdeck/settings.html +44 -0
  48. flashdeck/templatetags/__init__.py +0 -0
  49. flashdeck/templatetags/flashdeck_tags.py +52 -0
  50. flashdeck/urls.py +31 -0
  51. flashdeck/views.py +392 -0
  52. flashdeck/wagtail_hooks.py +109 -0
  53. flashdeck/wagtail_views.py +106 -0
@@ -0,0 +1,146 @@
1
+ # Generated by Django 5.2.18 on 2026-11-08 17:15
2
+
3
+ import django.core.validators
4
+ import django.db.models.deletion
5
+ import django.utils.timezone
6
+ import flashdeck.images
7
+ import flashdeck.models
8
+ import modelcluster.fields
9
+ from django.conf import settings
10
+ from django.db import migrations, models
11
+
12
+
13
+ class Migration(migrations.Migration):
14
+
15
+ initial = True
16
+
17
+ dependencies = [
18
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
19
+ ]
20
+
21
+ operations = [
22
+ migrations.CreateModel(
23
+ name='Card',
24
+ fields=[
25
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
26
+ ('key', models.SlugField(help_text='Identifies the card within its deck, such as in exported bundles.', max_length=100)),
27
+ ('prompt', models.TextField(blank=True)),
28
+ ('image', models.FileField(blank=True, help_text='PNG, JPEG, WebP or SVG. Photographs are reduced in size and their metadata removed.', upload_to=flashdeck.models.card_image_path, validators=[django.core.validators.FileExtensionValidator(['png', 'jpg', 'jpeg', 'webp', 'svg']), flashdeck.images.validate_image])),
29
+ ('image_alt', models.CharField(blank=True, help_text='For screen readers. It must not give the answer away.', max_length=300, verbose_name='image description')),
30
+ ('image_credit', models.CharField(blank=True, help_text='Shown after the card is answered.', max_length=300)),
31
+ ('image_licence', models.CharField(blank=True, max_length=100)),
32
+ ('notes', models.TextField(blank=True, help_text='Shown after the card is answered.')),
33
+ ('position', models.IntegerField(default=0, help_text='New cards are introduced in order of this number.')),
34
+ ],
35
+ options={
36
+ 'ordering': ['deck', 'position', 'id'],
37
+ },
38
+ ),
39
+ migrations.CreateModel(
40
+ name='Deck',
41
+ fields=[
42
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
43
+ ('slug', models.SlugField(help_text='Unique within the subject.')),
44
+ ('title', models.CharField(max_length=200)),
45
+ ('description', models.TextField(blank=True)),
46
+ ('is_public', models.BooleanField(default=False, help_text='Anyone can practise a public deck; a private one only users with the permission “Can practise private decks”.', verbose_name='public')),
47
+ ('position', models.IntegerField(default=0, help_text='Decks are listed in order of this number.')),
48
+ ],
49
+ options={
50
+ 'ordering': ['subject', 'position', 'title'],
51
+ 'permissions': [('practise_private', 'Can practise private decks')],
52
+ },
53
+ ),
54
+ migrations.CreateModel(
55
+ name='Subject',
56
+ fields=[
57
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
58
+ ('slug', models.SlugField(unique=True)),
59
+ ('title', models.CharField(max_length=200)),
60
+ ('description', models.TextField(blank=True)),
61
+ ('language', models.CharField(blank=True, help_text='The language of the answers as a code (BCP 47), such as fr or de, for screen readers and phone keyboards; blank if none.', max_length=35)),
62
+ ('characters', models.CharField(blank=True, help_text='Characters offered as buttons for typing answers, separated by spaces, such as: é è ê ç', max_length=300)),
63
+ ('case_sensitive', models.BooleanField(default=False, help_text='If set, an answer that differs only in capitals is marked nearly right (for German nouns, for example); otherwise capitals are ignored.', verbose_name='case-sensitive')),
64
+ ('position', models.IntegerField(default=0, help_text='Subjects are listed in order of this number.')),
65
+ ],
66
+ options={
67
+ 'ordering': ['position', 'title'],
68
+ },
69
+ ),
70
+ migrations.CreateModel(
71
+ name='Answer',
72
+ fields=[
73
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
74
+ ('label', models.CharField(blank=True, help_text='Shown before the answer box.', max_length=100)),
75
+ ('text', models.CharField(max_length=500, verbose_name='answer')),
76
+ ('alternatives', models.TextField(blank=True, help_text='Other answers that are marked right, one per line.')),
77
+ ('sort_order', models.IntegerField(blank=True, editable=False, null=True)),
78
+ ('card', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='answers', to='flashdeck.card')),
79
+ ],
80
+ options={
81
+ 'ordering': ['sort_order', 'id'],
82
+ },
83
+ ),
84
+ migrations.AddField(
85
+ model_name='card',
86
+ name='deck',
87
+ field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cards', to='flashdeck.deck'),
88
+ ),
89
+ migrations.CreateModel(
90
+ name='Review',
91
+ fields=[
92
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
93
+ ('created', models.DateTimeField(db_index=True, default=django.utils.timezone.now)),
94
+ ('verdict', models.CharField(choices=[('right', 'Right'), ('nearly', 'Nearly right'), ('wrong', 'Wrong'), ('claimed', 'Claimed as right')], max_length=10)),
95
+ ('results', models.JSONField(default=list)),
96
+ ('state_before', models.JSONField(blank=True, null=True)),
97
+ ('card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reviews', to='flashdeck.card')),
98
+ ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='flashdeck_reviews', to=settings.AUTH_USER_MODEL)),
99
+ ],
100
+ options={
101
+ 'ordering': ['-created', '-id'],
102
+ },
103
+ ),
104
+ migrations.AddField(
105
+ model_name='deck',
106
+ name='subject',
107
+ field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='decks', to='flashdeck.subject'),
108
+ ),
109
+ migrations.CreateModel(
110
+ name='CardState',
111
+ fields=[
112
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
113
+ ('due', models.DateTimeField(db_index=True)),
114
+ ('fsrs', models.JSONField()),
115
+ ('created', models.DateTimeField(auto_now_add=True)),
116
+ ('card', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='states', to='flashdeck.card')),
117
+ ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='flashdeck_states', to=settings.AUTH_USER_MODEL)),
118
+ ],
119
+ options={
120
+ 'constraints': [models.UniqueConstraint(fields=('user', 'card'), name='flashdeck_cardstate_unique')],
121
+ },
122
+ ),
123
+ migrations.CreateModel(
124
+ name='ClaimedAnswer',
125
+ fields=[
126
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
127
+ ('text', models.CharField(max_length=500, verbose_name='claimed answer')),
128
+ ('status', models.CharField(choices=[('pending', 'To review'), ('accepted', 'Accepted'), ('rejected', 'Rejected')], db_index=True, default='pending', max_length=10)),
129
+ ('created', models.DateTimeField(auto_now_add=True)),
130
+ ('answer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='claims', to='flashdeck.answer')),
131
+ ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='flashdeck_claims', to=settings.AUTH_USER_MODEL)),
132
+ ],
133
+ options={
134
+ 'ordering': ['-created'],
135
+ 'constraints': [models.UniqueConstraint(fields=('answer', 'user', 'text'), name='flashdeck_claim_unique')],
136
+ },
137
+ ),
138
+ migrations.AddConstraint(
139
+ model_name='card',
140
+ constraint=models.UniqueConstraint(fields=('deck', 'key'), name='flashdeck_card_unique_key'),
141
+ ),
142
+ migrations.AddConstraint(
143
+ model_name='deck',
144
+ constraint=models.UniqueConstraint(fields=('subject', 'slug'), name='flashdeck_deck_unique_slug'),
145
+ ),
146
+ ]
@@ -0,0 +1,44 @@
1
+ # Generated by Django 5.2.18 on 2026-11-08 20:25
2
+
3
+ import flashdeck.models
4
+ from django.db import migrations, models
5
+
6
+
7
+ class Migration(migrations.Migration):
8
+
9
+ dependencies = [
10
+ ('flashdeck', '0001_initial'),
11
+ ]
12
+
13
+ operations = [
14
+ migrations.AddField(
15
+ model_name='cardstate',
16
+ name='frequency',
17
+ field=models.CharField(choices=[('more', 'More often'), ('normal', 'Normally'), ('less', 'Less often'), ('rarely', 'Rarely')], default='normal', max_length=10),
18
+ ),
19
+ migrations.AddField(
20
+ model_name='cardstate',
21
+ name='suspended',
22
+ field=models.BooleanField(default=False, help_text='Never shown in practice.', verbose_name='hidden'),
23
+ ),
24
+ migrations.AlterField(
25
+ model_name='cardstate',
26
+ name='due',
27
+ field=models.DateTimeField(blank=True, db_index=True, null=True),
28
+ ),
29
+ migrations.AlterField(
30
+ model_name='cardstate',
31
+ name='fsrs',
32
+ field=models.JSONField(blank=True, null=True),
33
+ ),
34
+ migrations.AlterField(
35
+ model_name='deck',
36
+ name='slug',
37
+ field=models.SlugField(help_text='Unique within the subject.', validators=[flashdeck.models.validate_not_reserved]),
38
+ ),
39
+ migrations.AlterField(
40
+ model_name='subject',
41
+ name='slug',
42
+ field=models.SlugField(unique=True, validators=[flashdeck.models.validate_not_reserved]),
43
+ ),
44
+ ]
@@ -0,0 +1,28 @@
1
+ # Generated by Django 5.2.18 on 2026-11-08 21:14
2
+
3
+ from django.db import migrations, models
4
+
5
+
6
+ class Migration(migrations.Migration):
7
+
8
+ dependencies = [
9
+ ('flashdeck', '0002_card_options'),
10
+ ]
11
+
12
+ operations = [
13
+ migrations.AddField(
14
+ model_name='deck',
15
+ name='reference',
16
+ field=models.TextField(blank=True, help_text="Reference material, in Markdown (tables included), shown with the cards' own reference pages and opened from a card."),
17
+ ),
18
+ migrations.AddField(
19
+ model_name='review',
20
+ name='looked_up',
21
+ field=models.BooleanField(default=False),
22
+ ),
23
+ migrations.AddField(
24
+ model_name='subject',
25
+ name='reference',
26
+ field=models.TextField(blank=True, help_text="Reference material, in Markdown (tables included), shown with the cards' own reference pages and opened from a card."),
27
+ ),
28
+ ]
File without changes
flashdeck/models.py ADDED
@@ -0,0 +1,325 @@
1
+ import secrets
2
+ from pathlib import PurePosixPath
3
+
4
+ from django.conf import settings
5
+ from django.core.exceptions import ValidationError
6
+ from django.core.validators import FileExtensionValidator
7
+ from django.db import models, transaction
8
+ from django.db.models.signals import post_delete
9
+ from django.dispatch import receiver
10
+ from django.utils import timezone
11
+ from modelcluster.fields import ParentalKey
12
+ from modelcluster.models import ClusterableModel
13
+
14
+ from .conf import setting
15
+ from .images import IMAGE_EXTENSIONS, prepare_image, validate_image
16
+ from .marking import Verdict, normalise
17
+ from .scheduling import Frequency
18
+
19
+ # Paths of the app's own pages, which a subject or deck must not take as its slug.
20
+ RESERVED_SLUGS = {"settings", "progress", "reference"}
21
+
22
+
23
+ def validate_not_reserved(value):
24
+ if value in RESERVED_SLUGS:
25
+ raise ValidationError(f"“{value}” is the name of one of the app's own pages.")
26
+
27
+
28
+ class Subject(models.Model):
29
+ """Something to learn, such as French or dog breeds, made up of decks."""
30
+
31
+ slug = models.SlugField(unique=True, validators=[validate_not_reserved])
32
+ title = models.CharField(max_length=200)
33
+ description = models.TextField(blank=True)
34
+ reference = models.TextField(
35
+ blank=True,
36
+ help_text="Reference material, in Markdown (tables included), shown with "
37
+ "the cards' own reference pages and opened from a card.",
38
+ )
39
+ language = models.CharField(
40
+ max_length=35,
41
+ blank=True,
42
+ help_text="The language of the answers as a code (BCP 47), such as fr or "
43
+ "de, for screen readers and phone keyboards; blank if none.",
44
+ )
45
+ characters = models.CharField(
46
+ max_length=300,
47
+ blank=True,
48
+ help_text="Characters offered as buttons for typing answers, separated by "
49
+ "spaces, such as: é è ê ç",
50
+ )
51
+ case_sensitive = models.BooleanField(
52
+ "case-sensitive",
53
+ default=False,
54
+ help_text="If set, an answer that differs only in capitals is marked nearly "
55
+ "right (for German nouns, for example); otherwise capitals are ignored.",
56
+ )
57
+ position = models.IntegerField(
58
+ default=0, help_text="Subjects are listed in order of this number."
59
+ )
60
+
61
+ class Meta:
62
+ ordering = ["position", "title"]
63
+
64
+ def __str__(self):
65
+ return self.title
66
+
67
+ def character_list(self):
68
+ return self.characters.split()
69
+
70
+
71
+ class Deck(models.Model):
72
+ """A set of cards on one topic within a subject."""
73
+
74
+ subject = models.ForeignKey(Subject, related_name="decks", on_delete=models.CASCADE)
75
+ slug = models.SlugField(
76
+ help_text="Unique within the subject.", validators=[validate_not_reserved]
77
+ )
78
+ title = models.CharField(max_length=200)
79
+ description = models.TextField(blank=True)
80
+ reference = models.TextField(
81
+ blank=True,
82
+ help_text="Reference material, in Markdown (tables included), shown with "
83
+ "the cards' own reference pages and opened from a card.",
84
+ )
85
+ is_public = models.BooleanField(
86
+ "public",
87
+ default=False,
88
+ help_text="Anyone can practise a public deck; a private one only users "
89
+ "with the permission “Can practise private decks”.",
90
+ )
91
+ position = models.IntegerField(
92
+ default=0, help_text="Decks are listed in order of this number."
93
+ )
94
+
95
+ class Meta:
96
+ ordering = ["subject", "position", "title"]
97
+ constraints = [
98
+ models.UniqueConstraint(
99
+ fields=["subject", "slug"], name="flashdeck_deck_unique_slug"
100
+ )
101
+ ]
102
+ permissions = [("practise_private", "Can practise private decks")]
103
+
104
+ def __str__(self):
105
+ return f"{self.subject}: {self.title}"
106
+
107
+
108
+ def card_image_path(card, filename):
109
+ """A random name in the subject's directory, so that the name of the file
110
+ cannot give the answer away."""
111
+ suffix = PurePosixPath(filename).suffix.lower().replace(".jpeg", ".jpg")
112
+ directory = setting("UPLOAD_DIR")
113
+ return f"{directory}/{card.deck.subject.slug}/{secrets.token_hex(8)}{suffix}"
114
+
115
+
116
+ class Card(ClusterableModel):
117
+ """A prompt (text, an image or both) and one or more answers to it."""
118
+
119
+ deck = models.ForeignKey(Deck, related_name="cards", on_delete=models.CASCADE)
120
+ key = models.SlugField(
121
+ max_length=100,
122
+ help_text="Identifies the card within its deck, such as in exported bundles.",
123
+ )
124
+ prompt = models.TextField(blank=True)
125
+ image = models.FileField(
126
+ upload_to=card_image_path,
127
+ blank=True,
128
+ validators=[FileExtensionValidator(IMAGE_EXTENSIONS), validate_image],
129
+ help_text="PNG, JPEG, WebP or SVG. Photographs are reduced in size and "
130
+ "their metadata removed.",
131
+ )
132
+ image_alt = models.CharField(
133
+ "image description",
134
+ max_length=300,
135
+ blank=True,
136
+ help_text="For screen readers. It must not give the answer away.",
137
+ )
138
+ image_credit = models.CharField(
139
+ max_length=300, blank=True, help_text="Shown after the card is answered."
140
+ )
141
+ image_licence = models.CharField(max_length=100, blank=True)
142
+ notes = models.TextField(blank=True, help_text="Shown after the card is answered.")
143
+ position = models.IntegerField(
144
+ default=0, help_text="New cards are introduced in order of this number."
145
+ )
146
+
147
+ class Meta:
148
+ ordering = ["deck", "position", "id"]
149
+ constraints = [
150
+ models.UniqueConstraint(
151
+ fields=["deck", "key"], name="flashdeck_card_unique_key"
152
+ )
153
+ ]
154
+
155
+ def __str__(self):
156
+ return " · ".join(self.prompt.split("\n")).strip() or self.key
157
+
158
+ def save(self, *args, **kwargs):
159
+ old_image = None
160
+ if self.pk:
161
+ old_image = (
162
+ type(self)
163
+ .objects.filter(pk=self.pk)
164
+ .values_list("image", flat=True)
165
+ .first()
166
+ )
167
+ if self.image and not self.image._committed:
168
+ prepared = prepare_image(self.image.file, self.image.name)
169
+ self.image.save(prepared.name, prepared, save=False)
170
+ super().save(*args, **kwargs)
171
+ if old_image and old_image != self.image.name:
172
+ _delete_file_on_commit(self.image.storage, old_image)
173
+
174
+
175
+ @receiver(post_delete, sender=Card)
176
+ def _delete_card_image(sender, instance, **kwargs):
177
+ if instance.image:
178
+ _delete_file_on_commit(instance.image.storage, instance.image.name)
179
+
180
+
181
+ def _delete_file_on_commit(storage, name):
182
+ transaction.on_commit(lambda: storage.delete(name))
183
+
184
+
185
+ class Answer(models.Model):
186
+ """One of a card's answers, each marked separately: a vocabulary card has one,
187
+ a conjugation table six (labelled je, tu, …)."""
188
+
189
+ card = ParentalKey(Card, related_name="answers", on_delete=models.CASCADE)
190
+ label = models.CharField(
191
+ max_length=100, blank=True, help_text="Shown before the answer box."
192
+ )
193
+ text = models.CharField("answer", max_length=500)
194
+ alternatives = models.TextField(
195
+ blank=True, help_text="Other answers that are marked right, one per line."
196
+ )
197
+ sort_order = models.IntegerField(null=True, blank=True, editable=False)
198
+
199
+ # Used by Wagtail's InlinePanel to keep the answers in order.
200
+ sort_order_field = "sort_order"
201
+
202
+ class Meta:
203
+ ordering = ["sort_order", "id"]
204
+
205
+ def __str__(self):
206
+ return f"{self.card} ({self.label})" if self.label else str(self.card)
207
+
208
+ def accepted(self):
209
+ """Every answer marked right, the model answer first."""
210
+ lines = (line.strip() for line in self.alternatives.splitlines())
211
+ return [self.text, *(line for line in lines if line)]
212
+
213
+ def add_alternative(self, text):
214
+ """Adds an answer to those marked right, unless it already is one."""
215
+ case_sensitive = self.card.deck.subject.case_sensitive
216
+ form = normalise(text, case_sensitive=case_sensitive)
217
+ if any(
218
+ normalise(a, case_sensitive=case_sensitive) == form for a in self.accepted()
219
+ ):
220
+ return False
221
+ self.alternatives = "\n".join([*self.accepted()[1:], text.strip()])
222
+ self.save(update_fields=["alternatives"])
223
+ return True
224
+
225
+
226
+ class CardState(models.Model):
227
+ """One user's progress with one card: its spaced-repetition (FSRS) state, and
228
+ the user's choices of how often it comes back and whether it is hidden.
229
+
230
+ A card hidden before it was ever answered has a state with no FSRS state and
231
+ no due date; showing it again deletes the state, so that it is new again.
232
+ """
233
+
234
+ user = models.ForeignKey(
235
+ settings.AUTH_USER_MODEL,
236
+ related_name="flashdeck_states",
237
+ on_delete=models.CASCADE,
238
+ )
239
+ card = models.ForeignKey(Card, related_name="states", on_delete=models.CASCADE)
240
+ due = models.DateTimeField(null=True, blank=True, db_index=True)
241
+ fsrs = models.JSONField(null=True, blank=True)
242
+ suspended = models.BooleanField(
243
+ "hidden", default=False, help_text="Never shown in practice."
244
+ )
245
+ frequency = models.CharField(
246
+ max_length=10, choices=Frequency.choices, default=Frequency.NORMAL
247
+ )
248
+ created = models.DateTimeField(auto_now_add=True)
249
+
250
+ class Meta:
251
+ constraints = [
252
+ models.UniqueConstraint(
253
+ fields=["user", "card"], name="flashdeck_cardstate_unique"
254
+ )
255
+ ]
256
+
257
+ def __str__(self):
258
+ return f"{self.user}: {self.card}"
259
+
260
+
261
+ class Review(models.Model):
262
+ """One answer to a card by a user, as marked."""
263
+
264
+ user = models.ForeignKey(
265
+ settings.AUTH_USER_MODEL,
266
+ related_name="flashdeck_reviews",
267
+ on_delete=models.CASCADE,
268
+ )
269
+ card = models.ForeignKey(Card, related_name="reviews", on_delete=models.CASCADE)
270
+ created = models.DateTimeField(default=timezone.now, db_index=True)
271
+ verdict = models.CharField(max_length=10, choices=Verdict.choices)
272
+ # One entry per answer: {"answer": id, "given": text, "verdict": verdict,
273
+ # "expected": the accepted answer compared with}.
274
+ results = models.JSONField(default=list)
275
+ # The card's FSRS state before this review (None for a new card), so that it
276
+ # can be rescheduled if the user claims that an answer was right.
277
+ state_before = models.JSONField(null=True, blank=True)
278
+ # The user opened the reference before marking, so a right answer is scheduled
279
+ # as nearly right.
280
+ looked_up = models.BooleanField(default=False)
281
+
282
+ class Meta:
283
+ ordering = ["-created", "-id"]
284
+
285
+ def __str__(self):
286
+ return f"{self.user}: {self.card} ({self.get_verdict_display()})"
287
+
288
+
289
+ class ClaimedAnswer(models.Model):
290
+ """An answer that a user said was right, although it matched none of the
291
+ accepted answers. It is marked right for that user from then on; accepting it
292
+ adds it to the answers marked right for everyone."""
293
+
294
+ class Status(models.TextChoices):
295
+ PENDING = "pending", "To review"
296
+ ACCEPTED = "accepted", "Accepted"
297
+ REJECTED = "rejected", "Rejected"
298
+
299
+ answer = models.ForeignKey(Answer, related_name="claims", on_delete=models.CASCADE)
300
+ user = models.ForeignKey(
301
+ settings.AUTH_USER_MODEL,
302
+ related_name="flashdeck_claims",
303
+ on_delete=models.CASCADE,
304
+ )
305
+ text = models.CharField("claimed answer", max_length=500)
306
+ status = models.CharField(
307
+ max_length=10, choices=Status.choices, default=Status.PENDING, db_index=True
308
+ )
309
+ created = models.DateTimeField(auto_now_add=True)
310
+
311
+ class Meta:
312
+ ordering = ["-created"]
313
+ constraints = [
314
+ models.UniqueConstraint(
315
+ fields=["answer", "user", "text"], name="flashdeck_claim_unique"
316
+ )
317
+ ]
318
+
319
+ def __str__(self):
320
+ return self.text
321
+
322
+ def save(self, *args, **kwargs):
323
+ super().save(*args, **kwargs)
324
+ if self.status == self.Status.ACCEPTED:
325
+ self.answer.add_alternative(self.text)