Django表单数据不保存到DB(sqlite)

时间:2017-06-15 20:17:56

标签: python django django-forms

当我提交表单时,我的终端说:“POST / polls / HTTP / 1.1”200 851.当我通过python manage.py shell检查时,表单数据没有显示出来。我不确定为什么数据没有保存到db,这是sqlite。我认为当我尝试保存表单时,错误位于视图部分。我读过不同的帖子,似乎有类似的问题,但我似乎无法弄清楚我的问题是什么。

型号:

from django.db import models
class Stores(models.Model):
    name  = models.CharField(max_length=200)
    address = models.CharField(max_length=30)
    city = models.CharField(max_length=30)
    state = models.CharField(max_length=2)
    def __str__(self):
        return "%s (%s,%s) %s" % (self.name, self.city, self.state, 
        self.address)

形式:

from django.forms import ModelForm
from mysite.polls.models import Stores

   class StoreForm(ModelForm):
       class Meta:
           model = Stores
           fields = ['name','address','city','state']

观点:

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse

from mysite.polls.models import Stores
from mysite.polls.forms import StoreForm

def index(request):
    downtown_store = Stores.objects.get(name="Corporate")
    store_name = downtown_store.name
    store_address = downtown_store.address
    store_state = downtown_store.state
    if request.method == 'Post':
        form = StoreForm(request.POST)
            if form.is_valid():
               form.save(commit=True)
               return HttpResponseRedirect(reverse('index'))
   else:
        form = StoreForm() 

       context = {'store_name':store_name, 'store_address':store_address, 'store_state':store_state, 'form':form,} 

       return render(request,'polls/index.html',context)

模板:

    <html>
    <body>
        <h1> {{store_name}} </h1>
        <h2> {{store_address}} </h2>
        <h3> {{store_state}} </h3>

    <form action="{% url "index" %}"  method="post">
      {% csrf_token %}
      {{ form }}
      <input type="submit" value="Submit" />
   </form>

1 个答案:

答案 0 :(得分:1)

该方法需要全部上限。

if request.method == 'POST':

注意,视图的最后两行需要向左移动一个缩进。