首页 > 解决方案 > 部署系统时如何向特定对象发送多个通知?

问题描述

我正在尝试向特定用户发送通知。它适用于我的本地主机,我可以向用户发送任意数量的通知,但是当我尝试部署它时,我只能向特定用户发送 1 个通知。当我尝试再次向同一用户发送通知时,我收到一条错误消息

重复的键值违反了唯一约束“user_notifications_usernotification_sender_id_key”和详细信息:键 (sender_id)=(1) 已存在。我使用 heroku 部署我的系统和 Postgresql 作为我的数据库。

我已经尝试将我的发件人关系从 更改OneToOneFieldForeignkey,但我仍然遇到同样的错误。

蟒蛇模型.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)

视图.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)

表格.py

class SendNotificationForm(forms.ModelForm):
    class Meta:
        model = UserNotification
        fields = ['receiver','concern_type','content']

标签: pythonpostgresqlherokudjango-modelsdjango-views

解决方案


我刚刚解决了我的错误。我只是重置我的数据库并在 heroku 命令上迁移它


推荐阅读