将数据从 models.py 传递到 views.py 并显示给用户

pass data from models.py to views.py and show it to user

我想在用户每次填写一个时给他们 10 分 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 方法来添加硬币。