Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can someone help? Sending notifications to all users or some users in django forms

I want to send a single notification message to multiple users or all users. I have tried many to many fields but the sent to id won’t save the i.d’s of the users that i have sent the message to.

Models.py

class Notifications(models.Model):
    id=models.AutoField(primary_key=True)
    sent_to = models.ManyToManyField(CustomUser)
    message = models.TextField(null=True)
    message_reply = models.TextField(null=True)
    created_at=models.DateTimeField(auto_now_add=True)
    updated_at=models.DateTimeField(auto_now=True)

Views.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def add_notification(request):

    notifs = Notifications.objects.all()
    users = CustomUser.objects.filter(is_staff=True)

    if request.method == 'POST':
        form = AddNotifForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.message_reply = "none"
            instance.save()
            sent_to = form.cleaned_data.get('sent_to')
            messages.success(request, f'Message has been successfully sent .')
            return redirect('add_notif')
    else:
        form = AddNotifForm()

    context={

        'notifs' : notifs,
        'form' : form,
        'users' : users,
    }

    template_name ='main-admin/add-notif.html'
    return render(request, template_name, context)

Forms.py

class AddNotifForm(forms.ModelForm):

    sent_to = forms.ModelMultipleChoiceField(
            queryset=CustomUser.objects.filter(is_staff=True).exclude(is_superuser=True),
            widget=forms.CheckboxSelectMultiple,
            required=True)

    class Meta: 
        model = Notifications
        fields = ['sent_to', 'message']

>Solution :

From the docs:

every time you save a form using commit=False, Django adds a save_m2m() method to your ModelForm subclass. After you’ve manually saved the instance produced by the form, you can invoke save_m2m() to save the many-to-many form data.

So you’ll have to call save_m2m() after instance.save() if you are using commit=False:

        instance = form.save(commit=False)
        instance.message_reply = "none"
        instance.save()
        form.save_m2m() # <-- Add this
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading