0

I'm trying to get the data from a POST but I can't use the 'request' it says "NameError: name 'request' is not defined". I tried using 'import request' it says that 'No module named 'request''. This code is from my views.py that working well. Is it possible to use this also in a python file? or there is another way? I also add request to the def update_extend_traces_traceselect(request).

in my graph.py

 def update_extend_traces_traceselect(request):
    if request.method == 'POST':
        post_data = json.loads(request.body.decode("utf-8"))
        value = post_data.get('data')
        print(value)
  • 2
    If the `update_extend_traces_traceselect` is a handler, then you should pass a request parameter. `def update_extend_traces_traceselect(request):` – DeeStarks Sep 06 '22 at 09:50
  • 1
    request is passed to the view function. If update_extend_traces_traceselect is configured as view handler in your urls.py, then you should define it as `def update_extend_traces_traceselect(request)` – treuss Sep 06 '22 at 09:51
  • 1
    You can't pass request as an argument to every function in django. It has to be a view function. If it is a regular function it will not recognize request. – Aman Sep 06 '22 at 10:08
  • @Aman it there another way to get that data in a regular function? – Cason Mercadejas Sep 06 '22 at 10:10
  • @CasonMercadejas you can call regular function inside your view. that way you can pass current request – Aman Sep 06 '22 at 15:54

1 Answers1

0

You forgot to add request to the function parameter.

def update_extend_traces_traceselect(request):
    if request.method == 'POST':
        post_data = json.loads(request.body.decode("utf-8"))
        value = post_data.get('data')
        print(value)

Read more about the Django request object and how to use it in function-based views.

Marco
  • 2,371
  • 2
  • 12
  • 19
  • @CasonMercadejas If it's printing that, then you're not POSTing a JSON object that has a `None` key. – AKX Sep 06 '22 at 09:53
  • Your question was about using request in a function based view. Now it seems that you have another question related to reading POST data. I think this should be a new question. You can also read more here https://stackoverflow.com/a/11336580/4151233 – Marco Sep 06 '22 at 09:56