Field 'id' expected a number but got

后端 未结 3 585
鱼传尺愫
鱼传尺愫 2021-01-25 17:04

i want to delete and edit notes in my django app, but i am struck on this error for long Error : \"TypeError at /delete/1/ Field \'id\' expected a number but got .

相关标签:
3条回答
  • 2021-01-25 17:51

    Please see this answer if you were playing with API(Rest Framework of Django) I got this error and I solved it by changing True to False while serializing the object.

    @api_view(['GET'])
    def event_detail(request, pk):
        try:
            event = Event.objects.get(id=pk)
            # This is the line I have made changes True to False.
            serializer = EventSerializer(event, many=False)
            return Response(serializer.data)
        except:
            return render(request, "404_page.html")
    
    0 讨论(0)
  • 2021-01-25 17:52

    You need to change here:

    from django.shortcuts import render
    
    def del_note(request, note_id):
    
        x = Note.objects.get(id = note_id)  # <-- Here
        print (x) // tried for degugging
        x.delete()
        return redirect("/")   
    
    
    def edit_note(request, note_id):
        x = Note.objects.get( id = note_id) # <-- Here
        form = NoteForm(request.POST or None, instance=x)
        if request.method == "POST":
            if form.is_valid():
                form.save()
                return redirect("/")
        return render(request, 'edit_template.html', context={'form':form,'sticky':x})
    
     # edit_template.html
     <form action="{% url 'edit_note' sticky.id %}" method="POST">
          {% csrf_token %}
          <div class="inputContainer">
              {{ form.as_p }}
              <input type="submit" placeholder="Edit Note" value="Edit note">
          </div>
     </form>
    

    The error was occurring because you passed id, but you should pass note_id instead.

    0 讨论(0)
  • 2021-01-25 17:56

    You have to use note_id instead of id as below...

    def del_note(request, note_id):
        x = Note.objects.get(id = note_id)
        # Your logic 
    
    
    def edit_note(request, note_id):
        x = Note.objects.get(id = note_id)
        # Your logic
    

    If you want to edit then you can do it like...

    def edit_note(request, note_id):
        x = Note.objects.get(id = note_id)
        x.field_name_1 = new_val_1
        x.field_name_2 = new_val_2
        # and so on for other fields...
        x.save()
    
    
        # Your logic
    
    0 讨论(0)
提交回复
热议问题