【发布时间】:2019-12-15 16:29:33
【问题描述】:
我正在尝试向特定用户发送通知。它适用于我的本地主机,我可以向用户发送任意数量的通知,但是当我尝试部署它时,我只能向特定用户发送 1 个通知。当我尝试再次向同一用户发送通知时,我收到一条错误消息,提示
重复键值违反唯一约束 “user_notifications_usernotification_sender_id_key”和详细信息:密钥 (sender_id)=(1) 已经存在。我使用 heroku 来部署我的系统和 Postgresql 作为我的数据库。
我已经尝试将我的发件人关系从 OneToOneField 更改为 Foreignkey,但我仍然收到同样的错误。
蟒蛇 模型.py
class UserNotification(models.Model):
sender= models.OneToOneField(User,on_delete=models.CASCADE,related_name='user_sender',unique=True)
receiver= models.ForeignKey(User,on_delete=models.CASCADE,related_name='user_receiver',unique=False)
concern_type= models.CharField(max_length=100,choices=CHOICES)
content = models.TextField(max_length=255,blank=False)
date_sent= models.DateTimeField(default = timezone.now)
views.py
def send_notifications(request):# form that admin can send notification to a specific user.
if request.method == 'POST':
form = SendNotificationForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.sender = request.user
receiver = instance.receiver
instance.save()
messages.success(request,'Your notification was sent successfully!')
return redirect('send-notification-form')
else:
form = SendNotificationForm()
template_name = ['user-forms/send-notification-form.html']
context = {'form':form}
return render(request,template_name,context)
def user_notifications(request): # notification module of users
notifications = UserNotification.objects.filter(receiver__exact=request
.user).order_by('-date_sent')
context = { 'notifications':notifications }
template_name = ['notification.html']
return render(request,template_name,context)
forms.py
class SendNotificationForm(forms.ModelForm):
class Meta:
model = UserNotification
fields = ['receiver','concern_type','content']
【问题讨论】:
-
sender模型中的UserNotification字段是OneToOne。这意味着任何发件人只能发送一个UserNotification。我不确定为什么这似乎让一个用户在您的本地计算机上发送多个UserNotifications;不应该。 (请注意,这是对发送者而非接收者的约束。) -
是的,但我已经尝试将我的 Usernotification 中的发件人字段更改为外键,它在我的本地工作,但是当我部署时,我仍然得到同样的错误。
-
嗯,你在这里分享的代码肯定有我上面概述的问题。如果您在使用
ForeignKey时仍然遇到问题,请分享 那个 代码。 -
类 UserNotification(models.Model): sender=models.ForeignKey(User,on_delete=models.CASCADE,related_name='user_sender',unique=False) receiver= models.ForeignKey(User,on_delete= models.CASCADE,related_name='user_receiver',unique=False) concern_type= models.CharField(max_length=100,choices=CHOICES) content = models.TextField(max_length=255,blank=False) date_sent= models.DateTimeField(default = timezone.now)
-
它可以工作并且用户在我的本地机器上多次收到我的通知,但是当我部署它时它没有工作。
标签: python postgresql heroku django-models django-views