Untitled

mail@pastecode.io avatar
unknown
python
2 years ago
2.5 kB
2
Indexable
Never
Account/models

class MessageModel(models.Model):
    id = models.AutoField(primary_key=True)
    sender = models.ForeignKey(get_user_model(), related_name='sender', on_delete=models.CASCADE)
    receiver = models.ForeignKey(get_user_model(), related_name='receiver', on_delete=models.CASCADE)
    message = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.message


Account/forms
MessageModel -> include this

class MessageForm(ModelForm):
    class Meta:
        model = MessageModel
        fields = ('message', 'receiver')


Account/views
MessageForm,MessageModel -> include this

@login_required()
def messaging(request,pk_test):
    if request.user.username==pk_test or request.user.groups.filter(name='Support').exists():
        get_user = CustomUser.objects.get(username=pk_test)
        profile = UserProfile.objects.get(user=get_user)
        if request.method == 'POST':
            form = MessageForm(request.POST)
            if form.is_valid():
                instance = form.save(commit=False)
                instance.sender = request.user
                instance.receiver = CustomUser.objects.get(username=form.cleaned_data['receiver'])
                instance.save()
                messages.success(request,'Your message has been sent successfully!')
                return redirect('user_profile', pk_test)
        else:
            form = MessageForm()
        return render(request, "Account/messaging.html",{'get_user': get_user, 'profile': profile , 'form': form})
    else:
        messages.success(request, 'You do not have permission to send a message to a user that is not you!')
        return render(request, 'home/HomePage.html')


# Display the messages that the user received
@login_required()
def inbox(request,pk_test):
    if request.user.username==pk_test or request.user.groups.filter(name='Support').exists():
        get_user = CustomUser.objects.get(username=pk_test)
        profile = UserProfile.objects.get(user=get_user)
        messages = MessageModel.objects.filter(receiver=request.user).order_by('created_at')
        return render(request, "Account/inbox.html",{'get_user': get_user, 'profile': profile , 'messages': messages})
    else:
        messages.success(request, 'You do not have permission to view this inbox!')
        return render(request, 'home/HomePage.html')