我试图向特定的用户发送通知。它可以在我的本地主机上工作,我可以向用户发送任意数量的通知,但是当我试图部署它时,我只能向特定用户发送一个通知。当我试图再次向同一个用户发送通知时,我会看到一个错误,即
重复键值违反唯一约束"user_notifications_usernotification_sender_id_key“和DETAIL: key (sender_id)=(1)已经存在。我使用heroku部署我的系统和Postgresql作为我的数据库。
我已经尝试将我的发件人关系从OneToOneField更改为Foreignkey,但是仍然会遇到相同的错误。
python models.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']发布于 2019-08-08 04:55:49
我刚解决了我的错误。我只是重置我的数据库,然后用heroku命令迁移它。
https://stackoverflow.com/questions/57404503
复制相似问题