Wizard
Wizard

Reputation: 22113

Exception Type: MultiValueDictKeyError when send POST request

When I try to post a create new article form, encounters such an error:

django.utils.datastructures.MultiValueDictKeyError: "'title'"
Exception Type: MultiValueDictKeyError
Exception Value:    
"'title'"

enter image description here

views.py, process the POST data and store it to database,

def create_article(request, block_id):
    block = Block.objects.get(id=block_id)

    if request.method == "GET":
        context = {'b':block}
        return render(request, "article/create_article.html", context)
    elif request.method == "POST":
        title = request.POST['title']
        content = request.POST['content']
        article = Article(block=block, title=title, content=content, status=0)
        article.save() # save to database
        return redirect(f"article/list/{ block_id }")

models.py

class Article(models.Model):
    STATUS = (
        (0,  'normal'),
        (-1, 'deleted'),
    )
    block = models.ForeignKey(Block, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    content = models.CharField(max_length=1000) # set the widget
    status = models.IntegerField(choices=STATUS)
    date_created = models.DateTimeField(default=datetime.now)
    date_updated = models.DateTimeField(auto_now=True)


    def __str__(self):
        return self.title

form template, utilize the bootstrap's style.

    <form class="form-horizontal" action="/article/create/{{ b.id }}" method="POST">
        {% csrf_token %}
      <div class="form-group">
        <label for="title" class="col-sm-1 control-label">Title</label>
        <div class="col-sm-11">
          <input type="text" class="form-control" id="title" placeholder="Write Title Later" >
        </div>
      </div>
      <div class="form-group">
        <label for="content" class="col-sm-1 control-label" >Content</label>
        <div class="col-sm-11">
          <textarea class="form-control" id="content" rows="10">Write Content Firslty.</textarea>
        </div>
      </div>

      <div class="form-group">
        <div class="col-sm-offset-1 col-sm-11">
          <button type="submit" class="btn btn-primary">Publish</button>
        </div>
      </div>
    </form>

It report the same error after I add name attribute to tag

        <div class="col-sm-11">
          <input type="text" class="form-control" id="title" name="title" placeholder="Write Title Later" >
        </div>

How to solve such a problem?

Upvotes: 3

Views: 3126

Answers (1)

Selcuk
Selcuk

Reputation: 59315

You are missing the name arguments for your inputs. The ids are only used by CSS and JS. Try using

<input type="text" class="form-control" name="title" id="title" placeholder="Write Title Later" >

instead of

<input type="text" class="form-control" id="title" placeholder="Write Title Later" >

Upvotes: 4

Related Questions