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

how to pass user id values to parameters in django?

I have a code where I need to pass the user_from id (the user from whom the message comes), but when I write user_from__pk writes an error that there is no such name

NameError: name ‘user_from__pk’ is not defined

My code:

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

views.py:

def send_chat(request):
    resp = {}
    User = get_user_model()
    if request.method == 'POST':
        post =request.POST
        u_from = UserModel.objects.get(id=post['user_from'])
        u_to = UserModel.objects.get(id=post['user_to'])
        messages = request.user.received.all()
        pk_list = messages.values(user_from__pk).distinct()
        correspondents = get_user_model().objects.filter(pk__in=list(pk_list))
        insert = chatMessages(user_from=u_from,user_to=u_to,message=post['message'], correspondents=correspondents)
        try:
            insert.save()
            resp['status'] = 'success'
        except Exception as ex:
            resp['status'] = 'failed'
            resp['mesg'] = ex
    else:
        resp['status'] = 'failed'

    return HttpResponse(json.dumps(resp), content_type="application/json")

models.py:

class chatMessages(models.Model):
    user_from = models.ForeignKey(User,
        on_delete=models.CASCADE,related_name="sent")
    user_to = models.ForeignKey(User,
        on_delete=models.CASCADE,related_name="received")
    message = models.TextField()
    date_created = models.DateTimeField(default=timezone.now)
    correspondents = models.ForeignKey(User,
        on_delete=models.CASCADE,related_name="correspondents", null=True)

    def __str__(self):
        return self.message

how can I pass the user_from id in the line:

pk_list = messages.values(user_from__pk).distinct()

>Solution :

.values() method accepts field names as string. So, it should be .values("user_from__pk")

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