chuck w
chuck w

Reputation: 1761

DJango user-profile - Each time that I modify a user's profile a new profile is created

This is likely a basic question, but I'm new to django . . .

I'm building a quiz app that allows users to answer questions in order. For example, users can only answer question 2 after they have successfully answered question one.

I'm using django.contrib.auth for user authentication, and have added a Profile model for extended User info, including keeping track of all of the questions each user has answered.

Here are my models:

class Question(models.Model):
  question_text = models.CharField(max_length=400)
  answer1 = models.CharField(max_length=200)
  times_solved = models.IntegerField(default=0)
  number = models.IntegerField(default=1, unique=True)

def __str__(self):
    return self.question_text

class Profile(models.Model):
  user = models.OneToOneField(User, on_delete=models.CASCADE)
  real_name = models.CharField(max_length=100)
  questions_answered = models.ManyToManyField(Question, blank=True, null=True)
  last_wrong_answer_made_on = models.DateTimeField('last wrong answer date', null=True, blank=True)

def __str__(self):
    return self.user.username

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

I also have an index view that lists all of the users along with the number of the last question that they have answered:

class IndexView(generic.ListView):
template_name = 'piratehunt/index.html'

context_object_name = 'user_list'

def get_queryset(self):

   return Profile.objects.all().order_by('-questions_answered__number')

And my index.html:

{% if user_list %}
    <ul>
    {% for user in user_list %}
        <li><a href="{% url 'piratehunt:user_detail' user.id %}">{{ team.user.username }} - {{ user.questions_answered.last.number }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No users have signed up.</p>
{% endif %}

My problem is in my QuestionDetail view. Every time I try to update a user's profile to indicate that he has solved a new question I end up creating a new profile for the user rather than simply updating the existing user profile. Here is the relevant code:

@login_required
def QuestionDetail(request, question_number):

user = User.objects.get(pk=request.user.id)
p = user.profile
last_question = user.profile.questions_answered.last()
current_question = Question.objects.get(number=(last_question.number + 1)) 
form = AnswerForm(request.POST)

if form.is_valid():
    attempt = form.cleaned_data.get('answer')
    if  attempt == current_question.answer1

   ##########This is what triggers the problem########
        user.profile.questions_answered.add(current_question)
        p.save()
        #make sure to reset the clock so that the team can answer the next question quickly
        current_question.times_solved = current_question.times_solved + 1
        current_question.save()

        messages.info(request, 'Great News!  You are correct! You can now go on to the next problem')
        return HttpResponseRedirect(reverse('piratehunt:index'))

    else:
        p.last_wrong_answer_made_on = now()
        p.save()

        messages.info(request, 'All guesses are wrong!  Try again in 2 hours.')
        return HttpResponseRedirect(reverse('piratehunt:index'))

else: #this is the GET for this view

    return render(request, 'piratehunt/question_answer.html', {'form': form, 'question': current_question.question_text})

The end result is that once a user has answered two questions he appears 2 times in the index.html, and once he has answered three questions he appears 3 times, etc., etc.

Here's what it looks like:

enter image description here Why do I create a new profile each time I save the profile??

Upvotes: 0

Views: 207

Answers (1)

schillingt
schillingt

Reputation: 13731

You're not creating new profiles, but the queryset:

Profile.objects.all().order_by('-questions_answered__number')

is returning duplicates because number is on a many to many. You're asking for a a profile to be ordered by a property on a list of objects attached to it. You can either do an annotation on that list such as Min or Max or you can apply .distinct().

Min/Max:

from django.db.models import Max
Profile.objects.annotate(
    max_number=Max('questions_answered__number')
).order_by('-max_number')

Distinct:

Profile.objects.order_by('-questions_answered__number').distinct()

I'd recommend going the annotation route as it's more consistent. And you don't have to use the {{ user.questions_answered.last.number }} in your template either which makes another DB query.

Upvotes: 1

Related Questions