Home > Back-end >  how can I output a variable to a django template via HttpResponse?
how can I output a variable to a django template via HttpResponse?

Time:08-29

I need to output the correspondents variable to the django template via HttpResponse, but I can't think of how to do it correctly. 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(u_from.pk).distinct()
        correspondents = User.objects.filter(pk__in=list(pk_list))
        insert = chatMessages(user_from=u_from,user_to=u_to,message=post['message'])
        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)

    def __str__(self):
        return self.message

CodePudding user response:

A HttpResponse object does not take any inbound context. In order to process variables in a HTML template you need to render the template with variables. django uses the jinja2 engine to render the template in its built-in functions.

One of those function is the TemplateResponse which takes the request, a HTML Template and a context which is a dictionary of variables names as they will be used in the template and their content:

TemplateResponse(request, 'template.html', {'welcoming': 'Hello World'})

where 'Hello World' could also be a variable. The template could look like this:

<div>{{ welcoming }}</div>

which will render to something like

<div>Hello World</div>

Understanding where to put the templates can be tricky. In order to understand templates in django read the documentation on templates. I recommend to read the the article the django template language as well. When I write templates I frequently visit the reference for built-in template tags and filters.

  • Related