Home > database >  Why does it show TypeError: UpdateContent() got an unexpected keyword argument 'instance'?
Why does it show TypeError: UpdateContent() got an unexpected keyword argument 'instance'?

Time:11-24

Working on a simple project in Django 3.2 and trying to add an edit button, to edit the content of the page. To do that I did: views.py

def UpdateContent(request, pk):
    contents = todo.objects.get(id=pk)

    form = UpdateContent(instance=contents)

    if request.method == 'POST':
        form = UpdateContent(request.POST, instance=contents)
        if form.is_valid():
            form.save()
            return redirect('/')

    context = {'form': form}
    return render(request, 'html/update.html', context)

forms.py

class UpdateContent(ModelForm):
    class Meta:
        model = todo
        fields = ['content']

home.html

        <table class="table table-dark table-hover table-bordered">
          <thead>
            <tr id="tr-table">
              <th id="text-left">#</th>
              <th id="text-center">ITEMS</th>
              <th id="text-right"><i class="material-icons">&#xe872;</i></th>
            </tr>
          </thead>  
          <tbody>
            {% for all_item in all_items%}
              <tr>
                <th id="row" scope="row"> {{ forloop.counter }} </th>
                <td id="content">{{ all_item.content }}</td>
                <form action="delete_todo/{{all_item.id}}/" method="post">
                  {% csrf_token %}
                  <td class="text-right-delete">
                    <button id="btn-delete" class="btn btn-outline-danger">Delete</button> 
                  </td>
                </form>
                <td><a class="btn btn-outline-info" href="{% url 'todo:update' all_item.id %}">Edit</a></td>
             </tr>
            {% endfor %}
          </tbody>
        </table>

update.html

{% extends 'html/main.html' %}
{% load static %}

{% block content %}
    <form action="", method="POST">
    {% csrf_token %}
        {{form}}
        <input type="submit" name="Submit">
    </form>
{% endblock %}

But when I run the code it shows me this error TypeError: UpdateContent() got an unexpected keyword argument 'instance'

Would appreciate any response or suggestion. Thanks!

CodePudding user response:

This is because your form and view have same names. So the view itself getting called recursively.

def UpdateContent(request, pk):
    contents = todo.objects.get(id=pk)

    form = UpdateContent(instance=contents)

    if request.method == 'POST':
        form = UpdateContent(request.POST, instance=contents)
        if form.is_valid():
            form.save()
            return redirect('/')

    context = {'form': form}
    return render(request, 'html/update.html', context)
  • Related