Django“用户”对象没有属性“目标”

时间:2019-01-30 02:39:45

标签: python html django

我创建了一个函数,该函数可以为每个用户保存多个目标并将其显示在html文件中。问题是一旦注销,我将无法使用同一用户登录,因为我得到的错误User对象没有属性Goals,即使该对象已保存在数据库中。我的问题是导致此错误的原因是什么,我认为可能是对目标的引用,什么是潜在的解决方案?谢谢!

models.py

class Goals(models.Model):
    user = models.ForeignKey(User, null=True, default=None, on_delete=models.CASCADE)
    goal = models.CharField(max_length=2000)
    instrument = models.CharField(max_length=255, choices=instrument_list, blank=True)
    goal_date = models.DateField(auto_now=False, auto_now_add=False)

    def __str__(self):
        return self.Goals


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

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


class GoalsForm(ModelForm):
    class Meta:
        model = Goals
        exclude = ('user',)

views.py

def goal_creation(request):
    form = GoalsForm()
    cur_goals = Goals.objects.filter(user=request.user)

    if request.method == 'POST':
        form = GoalsForm(request.POST)

        if form.is_valid():
            goals = form.save(commit=False)
            goals.user = request.user
            goals.save()
            cur_goals = Goals.objects.filter(user=request.user)
            return redirect('/student/goal-progress')

        else:
            form = GoalsForm()

    context = {'form' : form, 'goals': cur_goals}
    return render(request, 'student/goal_creation.html', context)

2 个答案:

答案 0 :(得分:2)

您有两个问题:

  1. 您无法使用instance.Goals访问子实例;您应该使用instance.goals_set

  2. 您不能save查询集。您应该一个一个地保存Goals实例,即

for goal in instance.goals_set.all():
    goal.save()

话虽如此,我建议您将Goals类重命名为Goal,因为它会与Django的命名约定混淆。这也很有意义,因为每一行代表一个单独的goal

答案 1 :(得分:0)

尝试将related_name='goals'添加到Goals类的用户字段定义中:

user = models.ForeignKey(User, related_name='goals', null=True, default=None, on_delete=models.CASCADE)

然后,您应该能够在用户的对象上访问此属性: user_instance.goals.all()

可能需要迁移。

尽管这与问题没有直接关系,但我认为最好用单数形式的“目标”来命名模型类,这将与其他模型的名称一致(模型代表一个对象=一行),并且避免歧义自动复数。