Django:将表单数据保存到数据库

时间:2016-10-24 17:27:38

标签: django django-forms

我在我的Django项目中使用表单来获取人们的姓名和号码,以便日后联系。遵循了几个指南,包括Django文档,但它似乎没有用。我的测试POST没有出现在管理员中,也无法通过manage.py shell访问。我在我的代码中留下了多行注释,以显示我尝试的另一种方法以防万一。在我的manage.py runserver日志中不会抛出任何错误。

形式:

from django import forms

class SubscribeForm(forms.Form):
  name = forms.CharField(label='Your Name', max_length=100)
  phone_number = forms.CharField(label='Phone Number', max_length=12, min_length=10)

模板:

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

查看:

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from datetime import datetime

from .models import Person
from .forms import SubscribeForm

def home(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 = SubscribeForm(request.POST)
    # check whether it's valid:
    if form.is_valid():
        # process the data in form.cleaned_data as required
        p = form.save()
        '''
        name = form.cleaned_data['name']
        number = form.cleaned_date['phone_number']
        p = Person(name=name, phone_number=number, date_subscribed=datetime.now(), messages_recieved=0)
        p.save()
        '''
        # redirect to a new URL:
        return HttpResponseRedirect('/success/')
  # if a GET (or any other method) we'll create a blank form    
  else: 
    form = SubscribeForm()

  return render(request, 'texting/index.html', {'form': form})

我观看了几个视频并阅读了很多SO页面,但似乎仍然没有效果。

2 个答案:

答案 0 :(得分:2)

试试这个:

...
if form.is_valid():
    name = form.cleaned_data['name']
    number = form.cleaned_data['phone_number']
    p = Person(name=name, phone_number=number, date_subscribed=datetime.now(), messages_received=0)
    p.save()
...

form.save()步骤是不必要的。

ETA:

您也可以尝试使用ModelForm和一些默认值或自定义保存方法,如下所示:

class Person(models.Model):
    name = models.CharField(max_length=96)
    phone_number = models.CharField(max_length=12)
    date_subscribed = models.DateTimeField(default=datetime.now())
    messages_received = models.IntegerField(default=0)

from django.forms import ModelForm

class SubscribeForm(ModelForm):
    class Meta:
        model = Person
        exclude = ('date_subscribed','messages_received')

如果你使用ModelForm,那么你必须完成form.save()。

答案 1 :(得分:0)

p = Person(name=name, 
           phone_number=number, 
           date_subscribed=datetime.now(), 
           messages_received=0)
p.save()

删除这两行。 添加如下:

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE','YourProjectName.settings')

import django
django.setup()

Person.objects.get_or_create()