Z
Z
Zer072019-05-08 18:18:42
Django
Zer07, 2019-05-08 18:18:42

How to return json using HttpResponce?

There is a view:

class CategoriesListView(ListView):
      model = Category

      queryset = Category.objects.all()
      context_object_name = 'categories'
      template_name = 'bikes_site/categories_list.html'

And this template:
<ul>
    {% for category in categories %}
    <li> <a href="{{ category.get_absolute_url }}" class="btn btn-light mb-2" >{{ category.name|title }}</a></li>
    {% endfor %}
</ul>

You need to do something like this HttpResponce(json.dumps(name: Category.name)).
Here is the test
def test_categories(setup):
    client = Client()
    response = client.get('/categories/')
    assert response.status_code == 200
    assert json.loads(response.content.decode('utf-8'))[2]['name'] == 'Квадроциклы'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FulTupFul, 2019-05-08
@FulTupFul

As I understand it, you are rendering html, and not giving pure json. You can get the rendered context with Context

response = client.get('/categories/')
response.context['name']

https://docs.djangoproject.com/en/2.2/topics/testi...
If application/json is the answer then:
response = client.get('/categories/')
response.json()['name']

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question