我已经创建了一个函数,可以为每个用户保存多个目标,并将它们显示在一个html文件中。问题是一旦我注销,我就不能以相同的用户重新登录,因为我得到了错误的User object has no attribute 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)发布于 2019-01-30 10:48:11
您有两个问题:
instance.Goals访问子实例;您应该使用instance.goals_set。save一个查询集。您应该逐个保存Goals实例,即for goal in instance.goals_set.all():
goal.save()话虽如此,我建议您将Goals类重命名为Goal,因为这会与Django的命名约定产生混淆。这也很有意义,因为每一行代表一个goal。
发布于 2019-01-30 19:27:02
尝试将related_name='goals'添加到目标类的用户字段定义:
user = models.ForeignKey(User, related_name='goals', null=True, default=None, on_delete=models.CASCADE)然后,您应该能够访问用户的对象上的这个属性:user_instance.goals.all()。
可能需要迁移。
虽然这与问题没有直接关系,但我认为最好将模型类命名为单数形式的"Goal",它将与其他模型的名称保持一致(模型代表一个object=one行),并避免自动复数中的歧义。
https://stackoverflow.com/questions/54432643
复制相似问题