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

发布于 2025-02-04 01:01:16 字数 2721 浏览 1 评论 0原文

我想在用户每次填写一个调查时给用户10点,因此我在上面有此代码,现在如何在填写一个

型号

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

后将10点添加到自我用户中。 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/')

所以,如果我想在用户完成一项调查后,我必须要做什么

I want to give users ten point each time they fill out one Survey , so i have this code above and now how to add the 10 point to self user after he fill out one

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/')

so what i must to do if i want to add 10 point to user after he complete one survey

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

第七度阳光i 2025-02-11 01:01:16

如果submit_survey是一个需要身份验证的调用,则用户将在请求request.user上显示。

通过添加request.user.give_coins(count = 10)将硬币添加到submit_query方法。

If submit_survey is a call that requires authentication the user will be present on the request request.user.

Add the coins by adding request.user.give_coins(count=10) to the submit_query method.

北陌 2025-02-11 01:01:16

您可以

  1. 使用以事件驱动的工具(也许很难但原则上的)
  2. 设置 give_coin befor 参与者

。请注意,硬币是在您的诱惑者模型上

you have 2 way

  1. work with event driven tools(maybe hard but principled)
  2. set give_coin befor participant.save() on submit_survey

anyway I din't notice, coin is on your absUser model but your Participant has nothing to do with it or relations

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文