django 名称未定义错误名称“F”

qlvxas9a  于 2023-02-10  发布在  Go
关注(0)|答案(1)|浏览(164)

当我尝试这个代码添加10点用户后,他填写了一个调查,它显示这个错误
但是,我遇到了一个问题。我得到了错误:

models.py", line 22, in give_coins
user.coins = F('coins') + count
NameError: name 'F' is not defined

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

views.py :

@require_http_methods(["POST"])
def submit_survey(request):
    request.user.give_coins(count=10)
    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/')

那么...这里的错误在哪里

9avjhtql

9avjhtql1#

在**”www.example.com“中导入“F”**models.py,如下所示:

from django.db.models import F

相关问题