尝试根据登录用户的用户名创建Model对象时的ValueError
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了尝试根据登录用户的用户名创建Model对象时的ValueError相关的知识,希望对你有一定的参考价值。
AIM
我正在尝试创建一个Alarm
对象,其中user
字段设置为登录User
的用户名。
问题与another question相同,我最近问过。但是,我重新构建了models.py和user=self.request.user.username
现在返回下面所述的错误。
尽管我现在正在使用Django的默认用户模型,但self.request.user.username
无法工作的原因是因为我还没有设置AUTH_USER_MODEL
?
ERROR
ValueError: Cannot assign "'sam_jones'": "Alarm.user" must be a "User" instance.
CODE
models.朋友
class Alarm(models.Model):
""" Model representing each Alarm """
alarm_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.OneToOneField(User, on_delete=models.CASCADE)
timezone = models.CharField(max_length=30)
city = models.CharField(max_length=30)
country = models.CharField(max_length=30)
time = models.DateTimeField()
temp_conditional = models.BooleanField()
surf_conditional = models.BooleanField()
temp_max = models.FloatField(blank=True, null=True)
temp_min = models.FloatField(blank=True, null=True)
surf_max = models.FloatField(blank=True, null=True)
surf_min = models.FloatField(blank=True, null=True)
def __str__(self):
return str(self.alarm_id)
views.朋友
class AlarmCreateView(LoginRequiredMixin, CreateView):
""" CreateView for User to create the Alarm object """
model = Alarm
...
def form_valid(self, form):
self.get_user_location(request, form)
return super().form_valid(form)
def get_user_location(self, request, form):
""" Function to get Profile's location from IP and create Alarm object """
...
alarm_object = Alarm.objects.create(
alarm_id=uuid.uuid4(),
user=self.request.user.username,
...
)
alarm_object.save()
答案
您必须提供用户实例,该实例可在qazxsw poi属性中找到。所以试试吧
request.user
You could do this also by reffering their
alarm_object = Alarm.objects.create(
alarm_id=uuid.uuid4(),
user=self.request.user,
...
)
as,
id
alarm_object = Alarm.objects.create(
alarm_id=uuid.uuid4(),
user=self.request.user.id,
...
)
异常提出,因为你将UNIQUE constraint failed
字段定义为user
到OneToOneField
模型,这意味着每个User
实例都与ATMOST一个用户相关。
以上是关于尝试根据登录用户的用户名创建Model对象时的ValueError的主要内容,如果未能解决你的问题,请参考以下文章
flask-login怎么实现用多个model登录,如管理员表,用户表分开登录