为什么我的Django表单未显示任何内容?

时间:2019-12-10 04:07:12

标签: python django django-forms django-templates

我正在关注一个教程,在该教程中,我们将创建一个表单来保存简单的对象参数。

代码如下:

forms.py

from django.forms import ModelForm
from .models import Item

class ItemForm(ModelForm):
    class Meta:
        model = Item
        fields = ['item_name', 'item_desc', 'item_price', 'item_image']

models.py

from django.db import models

class Item(models.Model):

    def __str__(self):
        return self.item_name

    item_name = models.CharField(max_length = 200)
    item_desc = models.CharField(max_length= 200)
    item_price = models.IntegerField()
    item_image = models.CharField(max_length=500, default ="https://i.jamesvillas.co.uk/images/jvh/holiday-destinations/resort/food-placeholder.jpg" )

urls.py

from . import views
from django.urls import path

urlpatterns = [
    path('', views.index, name = 'index'),
    path('item/', views.item, name = 'item'),
    path('info/', views.info, name = "info"),
    path('<int:item_id>/', views.detail, name = "detail" ),
    #add form
    path('add', views.create_item, name = "create"),
]

views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Item
from django.template import loader
from .forms import ItemForm
#Some code here

def create_item(request):
    form = ItemForm(request.POST or None)

    if (form.is_valid()):
        form.save()
        return redirect('food/index')

    return render(request, 'food/item-form.html', {'form': form})

food / item-form.html

<form method = "POST">
    {% csrf_token %}
    {{ form }}
    <button type= "Submit" >Save</button>
</form>

现在,当我转到http://localhost:8000/food/add时,它将显示一个空白页面!我已经按照教程的完全相同方式进行了操作,为什么我的项目无法正常工作?

1 个答案:

答案 0 :(得分:0)

更正您的views.py

from django.http import HttpResponseRedirect

from django.shortcuts import render

from .forms import NameForm

def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
    # create a form instance and populate it with data from the request:
    form = NameForm(request.POST)
    # check whether it's valid:
    if form.is_valid():
        # process the data in form.cleaned_data as required
        # ...
        # redirect to a new URL:
        return HttpResponseRedirect('/thanks/')

# if a GET (or any other method) we'll create a blank form
else:
    form = NameForm()

return render(request, 'name.html', {'form': form})