Передавать данные из models.py в views.py и показывать их пользователю

Я хочу давать пользователям десять очков каждый раз, когда они заполняют один Survey, поэтому у меня есть этот код выше, а теперь как добавить 10 очков пользователю после того, как он заполнит один

models.py :

class User(AbstractUser):
    user_pic = models.ImageField(upload_to='img/',default="",null=True, blank=True)
    coins = models.IntegerField(default=10)
    def get_image(self):
        if self.user_pic and hasattr(self.user_pic, 'url'):
            return self.user_pic.url
        else:
            return '/path/to/default/image'
    def give_coins(user, count):
        user.coins = F('coins') + count
        user.save(update_fields=('coins',))
        user.refresh_from_db(fields=('coins',))



class Survey(models.Model):
    name = models.CharField(max_length=200)
    published_on = models.DateTimeField('Published DateTime')

    def __str__(self):
        return self.name

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.published_on <= now

    was_published_recently.admin_order_field = 'published_on'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'


class Participant(models.Model):

    survey = models.ForeignKey(Survey, on_delete=models.CASCADE)
    participation_datetime = models.DateTimeField('Participation DateTime')

    def __str__(self):
        return "Participant "+str(self.participation_datetime)


class Question(models.Model):
    survey = models.ForeignKey(Survey, on_delete=models.CASCADE)
    question_text = models.CharField(max_length=200)
    created_on = models.DateTimeField('Creation DateTime')

    def __str__(self):
        return self.question_text

views.py :

@register.inclusion_tag('survey/survey_details.html', takes_context=True)
def survey_details(context, survey_id):
    survey = Survey.objects.get(id=survey_id)
    return {'survey': survey}


@require_http_methods(["POST"])
def submit_survey(request):
    form_data = request.POST.copy()
    form_items = list(form_data.items())
    print("form_items", form_items)
    form_items.pop(0)  # the first element is the csrf token. Therefore omit it.
    survey = None
    for item in form_items:
        # Here in 'choice/3', '3' is '<choice_id>'.
        choice_str, choice_id = item
        choice_id = int(choice_id.split('/')[1])
        choice = Choice.objects.get(id=choice_id)
        if survey is None:
            survey = choice.question.survey
        choice.votes = choice.votes + 1
        choice.save()
    if survey is not None:
        participant = Participant(survey=survey, participation_datetime=timezone.now())
        participant.save()
    return redirect('/submit_success/')

Итак, что я должен сделать, если я хочу добавить 10 баллов пользователю после прохождения им одного опроса

Если submit_survey является вызовом, требующим аутентификации, user будет присутствовать в запросе request.user.

Добавьте монеты, добавив request.user.give_coins(count=10) к методу submit_query.

у вас есть 2 способа

  1. работать с инструментами, управляемыми событиями (возможно, сложно, но принципиально)
  2. установить give_coin перед participant.save() на submit_survey
  3. .

в любом случае я не заметил, монета находится на вашей модели absUser, но ваша Participant не имеет ничего общего с ней или отношениями

Вернуться на верх