我在其中一个视图中遇到(RelatedObjectDoesNotExist:UserProfile没有站点)错误但我能够在管理员中执行所有CRUD操作而没有任何错误。
django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: UserProfile has no site.
摘自models.py
class Sites(models.Model):
name = models.CharField(max_length=255, blank=True, null=True)
active = models.NullBooleanField()
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
logo_file_name = models.CharField(max_length=255, blank=True, null=True)
logo_content_type = models.CharField(max_length=255, blank=True, null=True)
logo_file_size = models.IntegerField(blank=True, null=True)
logo_updated_at = models.DateTimeField(blank=True, null=True)
logo_path = models.CharField(max_length=255, blank=True, null=True)
account_type = models.CharField(max_length=255, blank=True, null=True)
def __str__(self):
site_str = 'id = {}, name = {}'.format(self.id, self.name)
return site_str
class Meta:
managed = True
db_table = 'sites'
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
site = models.ForeignKey(Sites)
def __str__(self):
user_profile_str = '{}: {}'.format(self.user.username, str(self.site))
return user_profile_str
摘录表单views.py
@login_required
def client_list(request):
user_profile = UserProfile(user=request.user)
print(user_profile.user.username)
clients = Clients.objects.filter(site_rec=user_profile.site)
return render(request, 'snapreport/clients/all_clients.html', {'clients': clients})
答案 0 :(得分:3)
在此行中:user_profile = UserProfile(user=request.user)
您正在为该用户创建新的UserProfile。由于您没有为网站指定网站,user_profile.site
为None
(或尝试访问该网站会引发RelatedObjectDoesNotExist
)。
你可能想要:
user_profile = UserProfile.objects.get(user=request.user)
如果配置文件已经存在(假设它将具有site
)。