Home > Mobile >  Fixing "missing 1 required positional argument: 'id'" error when sending data fr
Fixing "missing 1 required positional argument: 'id'" error when sending data fr

Time:11-12

I have a Django Form where users inserts numeric values. I am sending the Ajax to a url but I keep receiving:

TypeError: addlog() missing 1 required positional argument: 'id'

I have tried to add the id in the url I got:

Reverse for 'addlog' with arguments '(2,)' not found. 1 pattern(s) tried: ['workout/addlog/\\Z']

Here is the views:

def addlog(request, id):
    workout = get_object_or_404(Workout, id=id)
    url = request.META.get('HTTP_REFERER')
        active_session = ActiveSession.objects.get(id=ActiveSession.objects.last().id)
    if request.headers.get('x-requested-with') == 'XMLHttpRequest' and request.method == 'POST':
        form = LogForm(request.POST)
        if form.is_valid():
            data = Log()
            data.log_workout = request.POST.get('log_workout')
            data.save()  
            context = {
                'log_workout': data.log_workout,
                 'id': workout.id,
            }
            html = render_to_string('my_gym/log_form.html', context, request=request)
            return JsonResponse({'form': html})
        else:
            print("The errors in addlog:",form.errors.as_data())
    else:
        print("What happened??")
    return HttpResponseRedirect(url)

Here is the form:

    <form  action="{% url 'my_gym:addlog' object.id %}" method="post">
        {% csrf_token %}
    </form>

Here is the script:

<script type="text/javascript">
    $(document).ready(function(event){
        $(document).on('click','#submitlog', function(event){
            event.preventDefault();
            var log_workout = $('#id_log_workout').val();

            $.ajax({
                type:'POST',
                url:'{% url 'my_gym:addlog' object.id %}',
                data:{'log_workout' : log_workout, csrfmiddlewaretoken':'{{csrf_token}}'},
                dataType:'json',
                success:function(response){
                    $('#log_form').html(response['form']),
                    console.log($('#log_form').html(response['form','div']));
                },
                error:function(rs, e){
                    console.log(rs.responseText);
                },
            });
        });
    });
</script>

Here is the url:

    path('workout/addlog/<int:id>', addlog, name='addlog'),

Here is the traceback:

Internal Server Error: /workout/addlog/2
Traceback (most recent call last):
  File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\User\Desktop\Project\my_gym\views.py", line 291, in addlog
    html = render_to_string('my_gym/log_form.html', context, request=request)
  File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\backends\django.py", line 62, in render
    return self.template.render(context)
  File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 175, in render
    return self._render(context)
  File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 167, in _render
    return self.nodelist.render(context)
  File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 966, in render_annotated
    return self.render(context)
  File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\defaulttags.py", line 472, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\urls\base.py", line 88, in reverse
    return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
  File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\urls\resolvers.py", line 828, in _reverse_with_prefix
    raise NoReverseMatch(msg)

My question

How can I fix this error knowing that I tried changing the workout.id to object.id still same error.

CodePudding user response:

There should be id in form instead of object.id since you are passing id from view so:

<form  action="{% url 'my_gym:addlog' id %}" method="POST">

Note: Always add / at the end of route so in urls.py it should be path('workout/addlog/<int:id>/'...)

CodePudding user response:

You did add id to the template's context

context = {
                'log_workout': data.log_workout,
                 'id': workout.id,
            }

So just change :

<form  action="{% url 'my_gym:addlog' object.id %}" method="post">

to :

 <form  action="{% url 'my_gym:addlog' id %}" method="post">
  • Related