将项目添加到数据库中而不在文本框中输入

时间:2019-02-05 17:27:16

标签: python django django-models django-forms django-views

我试图弄清楚如何在单击添加按钮后立即将默认项“ Item Code”插入“ List”数据库。我唯一能做的就是在文本框中插入我输入的字符串/字符。但是,当我单击“添加”按钮而未在文本框中输入任何内容时,出现此错误:

ValueError at /
The view home.views.index didn't return an HttpResponse object. It returned None instead.

到目前为止,这是我的代码:

models.py

from django.db import models
from django.utils import timezone

class List(models.Model):
    item = models.CharField(max_length=200)
    date = models.DateTimeField(default = timezone.now)

    def __str__(self):
        return self.item

views.py

from django.shortcuts import render
from .models import List
from .forms import ListForm
from django.contrib import messages


def index(request):
    context = {
        'items': List.objects.all()
    }

    if request.method == 'POST':
        form = ListForm(request.POST or None)

        if form.is_valid():
            form.save()
            messages.success(request, ('Item has been added to the list.'))
            return render(request, 'home/index.html', context)
    else:
        return render(request, 'home/index.html', context)

forms.py

from django import forms
from .models import List

class ListForm(forms.ModelForm):
    class Meta:
        model = List
        fields = [
            'item',
            'date'
        ]

index.html

<h1>To do list</h1>
{% if messages %}    
    {% for message in messages %}
        <p> {{ message }} </p>
    {% endfor %}
{% endif %}

<ul>
    {% if items %}
    {% for item in items %}
        <li>{{ item.item }}</li>
        <li>{{ item.date }}</li>
        <br>
    {% endfor %}
    {% endif %}
</ul>
<form method="POST">{% csrf_token %} 
    <input type="text" name="item">
    <input type="submit" value="Add">
</form>

1 个答案:

答案 0 :(得分:0)

删除else语句,并取消缩进。您总是希望返回该渲染的模板,除非您在成功发布后重定向。