输入表单数据时Django模型错误

时间:2018-09-17 21:47:44

标签: python django django-forms

Full Traceback

我是django的初学者,在将表单数据输入数据库时​​遇到了一些麻烦。我得到

`TypeError at /Info/
Info() got an unexpected keyword argument 'email'`

当我感觉自己做得正确时 这是我的模型。py

from django.db import models

# Create your models here.

class Info(models.Model):
    address = models.CharField(max_length=70)
    email = models.EmailField(max_length=32)

我的Views.py

def Info(request):
    if request.method == 'POST':
        form = InfoForm(request.POST)
        if form.is_valid():
            address = request.POST.get('address')
            email = request.POST.get('email')
            Facts = Info(email = email)
            Facts.save()
        else:
            form = InfoForm()
    return render(request, 'index/index.html', {'title': 'Info'})



def index(request):

    return render(request, 'index/index.html', {'title': 'Home'})

我的Forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class InfoForm(forms.Form):
   address = forms.CharField()
   email = forms.EmailField()

谢谢。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

由于您正在尝试新事物,因此Django是一个出色的框架,希望您能学到很多。因此,我在您的代码中注意到了几件事可能会有所帮助。因此,您特别遇到该错误的原因是因为您的命名存在冲突。您可以将Info作为类名,也可以将其用作视图。函数通常应小写。因此,如果您查看下面的内容,这应该可以解决您的错误。但我同意之前发表的评论,即您可能会使用ModelForm https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#django.forms.ModelForm

from wherever.models import Info
from wherever.forms import InfoForm

def info_view(request):
    if request.method == 'POST':
        form = InfoForm(request.POST)
        if form.is_valid():
            address = request.POST.get('address')
            email = request.POST.get('email')
            facts = Info(email=email, address=address)
            facts.save()
        else:
            form = InfoForm()
    return render(request, 'index/index.html', {'title': 'Info'})

答案 1 :(得分:0)

您的Info函数的名称与模型的名称相同,因此会遮盖模型的名称。

尝试更多类似的方法

def save_info(request):
    if request.method == 'POST':
        form = InfoForm(request.POST)
        if form.is_valid():
            address = request.POST.get('address')
            email = request.POST.get('email')
            Facts = Info(email = email)
            Facts.save()
        else:
            form = InfoForm()
    return render(request, 'index/index.html', {'title': 'Info'})

也就是说,您可以简化很多工作; ModelForm个实例具有一个save函数,可以将其当作模型对象来调用:

def save_info(request):
    if request.method == 'POST':
        form = InfoForm(request.POST)
        if form.is_valid():
            form.save()
        else:
            # report an appropriate error
            print("something went wrong!")
    return render(request, 'index/index.html', {'title': 'Info'})