How to fix this error: invalid literal for int() with base 10: 'undefined' and fix possibility for edit in edit function

Hi all! I have model Employee and same table in my local database. I need to have the possibility to edit any record and save it locally. When I tried to edit record with actual id I got this error: invalid literal for int() with base 10: ‘undefined’ . I made a research but can’t really find something helpful in my case. I have troubles with this from a few days so thanks a lot I hope my question is clear hope someone can help :slight_smile:

my edit function in views.py:

def staff_edit(request, id=0):

    #employees = Employee.objects.all()
    #print(employees)
    if request.method == 'GET':
        if id == 0:
            form = EmployeeEditForm()
        else:
            employees =  Employee.objects.get(pk=id)
            form = EmployeeEditForm(instance=employees)
        return render(request, 'staffedit.html', {'form': form})
    else:
        if id == 0:
            form = EmployeeEditForm(request.POST)
        else:
            employees =  Employee.objects.get(pk=id)
            form = EmployeeEditForm(request.POST, instance=employees)
        if form.is_valid():
            form.save()
            return redirect('feedback:index_employees')
        context = {'form': form} #when the form is invalid
    return render(request, 'staffedit.html', context)

this is my model.py for Employee:

class Employee(models.Model):
    coreapiemployee_id = models.CharField(max_length=100)
    webflow_id_employee = models.CharField(max_length=100, default=True)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100, default=True)
    email = models.EmailField(max_length=100)
    user_type = models.CharField(max_length=100)
    status = models.CharField(max_length=100, default=True)
    roles = models.ManyToManyField('Role', through='EmployeeRole')

    def __str__(self):
        return self.coreapiemployee_id + " " + self.email + self.first_name + self.last_name

this is my general html staff.html:

 $(document).ready(function() {
                     var data;
                     fetch("http://192.168.2.85:8000/displayEmployeesToFroentend/")
                        .then(response => response.json())
                        .then(json => data = json)
                        .then(() => {console.log(data);

                            let employees = JSON.parse(data.employees_json); 

                            var table = $('#datatable').DataTable( {
                            data:           employees,
                            select:         "single",
                            "columns": [
                                { "data": "fields.coreapiemployee_id"}, 
                                { "data": "pk"}, 
                                { "data": "fields.first_name" }, 
                                { "data": "fields.last_name" },
                                { "data": "fields.email" }, 
                                
                                    { render: function ( data, type, row ) {
                                        return '<a href="http://192.168.2.85:8000/staff/edit/' + row.coreapiemployee_id + '"><i class="far fa-edit fa-lg" aria-hidden="true"></i></a>'; 
                                    } },
                                    { render: function ( data, type, row ) {
                                        return '<i class="fa fa-plus-circle" aria-hidden="true"></i>';
                                    } },


                        ],
                        "order": [[1, 'asc']]

                    } )
                    
                })
                } ); 

pk is my primary key and that’s how I want to edit this records, via this pk

staffedit.html:

<div class="container">
    <div class="col-md-10.offset-md-1 mt-5">
      <div class="jumbotron">
        <h1 class="display-4">Edit Employee</h1>
        <hr class="my-4">
        <form action="" method="post" autocomplete="off">
            {% csrf_token %}
            {{form.as_p}}
            <button type="submit" class="btn btn-success"><i class="far fa-save"></i> Save</button>
        </form>
      </div>
    </div>
  </div>

my forms.py for EmployeeEditForm:

class EmployeeEditForm(ModelForm):
    class Meta:
        model = Employee
        fields = [
            'coreapiemployee_id',
            'first_name',
            'last_name',
            'roles',
    

urls.py:

path('staff/edit/<str:id>', views.staff_edit, name="staffedit"),

Kind regards,
Stela

Please post the complete traceback of the error you’ve received. It’s hard to locate a problem like this without knowing where in the code that exception is being thrown.

Also, the default id field is an integer field, so your URL would be:

path('staff/edit/<int:id>', views.staff_edit, name="staffedit"),

This may, or may not, be what’s causing the issue you’re reporting.

I tried with int a few days ago and it wasn’t work at all so I wasn’t think this was a problem, and now I changed my staff_edit function to receive the arguments def staff_edit(request, pk): and then I pass to urls.py path('staff/edit/<int:pk>' and now when I click on the action for edit I got Page not found (404) with the url http://192.168.2.85:8000/staff/edit/undefined and don’t get any other error but Page not found.
Do you think the logic in staff_edit is correct?

I don’t think anything without being able to see the complete traceback of the error and the code associated with that error.

I mean that I don’t have Traceback because all I got is:
DeepinScreenshot_select-area_20210129143435

don’t mind the port I changed it

Sorry, I was still addressing the original problem, not the revised issue.

So the issue is with the page before this one - you need to look at the page with the link that sent you to this one. Whatever generated the link to take you to “staff/edit/…” is what needs to be looked at.

Your URL is expecting the third component to be an integer, but you’re passing it the string “undefined”, causing the error. So the problem is what’s producing that link, not the target page.

That link you mean the page that is opening the django form when the edit is called?

I don’t understand what you’re trying to refer to here.

At some point, you’re on a page. (Let’s call it “X”) You click on a link on “X” that you are expecting to take you to a URL “staff/edit/…”. (Let’s call it “Y”).

The problem is on page “X”, not “Y”.

Oh okay sorry I just got this. I want to edit users via their primary key and just found that in my javascript function I am calling

return ‘<a href="http://192.168.2.85:7575/staff/edit/’ + row.coreapiemployee_id

but instead of this i need to call

return ‘<a href="http://192.168.2.85:7575/staff/edit/’ + row.pk

so now when I click on the action for edit I got TypeError at /staff/edit/6

int() argument must be a string, a bytes-like object or a number, not ‘builtin_function_or_method’

it looks like finally identify the id I want to edit.

I will post my Traceback from this too:

Internal Server Error: /staff/edit/6
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/usr/lib/python3/dist-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/lib/python3/dist-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/stela/feedbacksystem/feedback/views.py", line 288, in staff_edit
    employees =  Employee.objects.get(pk=id)
  File "/usr/lib/python3/dist-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/lib/python3/dist-packages/django/db/models/query.py", line 399, in get
    clone = self.filter(*args, **kwargs)
  File "/usr/lib/python3/dist-packages/django/db/models/query.py", line 892, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/usr/lib/python3/dist-packages/django/db/models/query.py", line 910, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/usr/lib/python3/dist-packages/django/db/models/sql/query.py", line 1290, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "/usr/lib/python3/dist-packages/django/db/models/sql/query.py", line 1315, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "/usr/lib/python3/dist-packages/django/db/models/sql/query.py", line 1251, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "/usr/lib/python3/dist-packages/django/db/models/sql/query.py", line 1116, in build_lookup
    lookup = lookup_class(lhs, rhs)
  File "/usr/lib/python3/dist-packages/django/db/models/lookups.py", line 20, in __init__
    self.rhs = self.get_prep_lookup()
  File "/usr/lib/python3/dist-packages/django/db/models/lookups.py", line 70, in get_prep_lookup
    return self.lhs.output_field.get_prep_value(self.rhs)
  File "/usr/lib/python3/dist-packages/django/db/models/fields/__init__.py", line 972, in get_prep_value
    return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method'

I’m guessing here is that there’s a conflict with you trying to use id as a variable name when it’s also the name of a built-in python function.

Try changing def staff_edit(request, id=0): to def staff_edit(request, pk=0):, and replace all references to id within that function to pk.

1 Like

WOW thank you so much!!! You saved my day!!! :slight_smile: that was the mistake that I made I mixed the python’s built-in function with mines. Thank you again and Best regards!