Reputation: 55
I am building a competition website where challenges will be released weekly. For each user I want to track if they have completed a challenge but cannot see how this would be done. Currently the challenges are stored as a model and am using the ListView and DetailView to display them.
from django.db import models
from django.contrib.auth.models import User
STATUS = (
(0, 'Draft'),
(1, 'Publish'),
)
class Challenge(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
release_date = models.DateTimeField()
preamble = models.TextField()
ciphertext = models.TextField()
plaintext = models.TextField()
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-release_date']
def __str__(self):
return self.title
Thank you in advance to anyone who helps me with this. Oh and a solution will be submitted and then checked with this form.
<div class='form'>
{% if user.is_authenticated %}
<textarea rows="10" name="plaintext" form="submitAnswer" wrap="soft" placeholder="Plaintext.."></textarea>
<form method="post" id="submitAnswer">
{% csrf_token %}
<input type="submit" value="Submit">
</form>
{% else %}
<p>Must be logged in to submit answer.</p>
{% endif %}
</div>
Upvotes: 0
Views: 43
Reputation: 2006
A really basic implementation is to add a ManyToManyField between your Challenge model and your the User model :
from django.conf import settings
class Challenge(models.Model):
users = models.ManyToManyField(settings.AUTH_USER_MODEL)
# Other fields...
In the above example, you can just activate the relationship if the user has passed the test.
Now, maybe, you want to add informations about this relationship. You can do it with 'through' argument. This model tells if a user has passed the challenge or not and how many tentatives has been done. Modify it as you wish.
from django.conf import settings
class Challenge(models.Model):
users = models.ManyToManyField(settings.AUTH_USER_MODEL,
through='ChallengeUsers')
# Other fields...
class ChallengeUsers(models.Model):
challenge = models.ForeignKey(Challenge, on_delete=models.CASCADE)
users = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
hasPassed = models.BooleanField(default=False)
tentatives = models.IntegerField()
Upvotes: 2