Django模型表单没有将所有字段保存到db

时间:2017-12-23 04:26:06

标签: python django

Django 1.11

Python 3.6

Allauth(暂时没有社交部分)

Sqlite3 db后端

我正在努力建立一个Django网站。 Allauth正在处理基本的注册/登录事务。我有一个用户配置文件与用户表具有外键关系 - 它本身不是扩展的用户模型。它是一个链接到用户表的模型。

我有一个显示个人资料表单的视图和表单。我有html5表单验证加上一些似乎有效的表单验证设置。如果我输入错误的表单数据并提交,则会报告各种字段错误。

如果我输入所有必需的数据并点击提交,则会在数据库中创建记录,但不会将所有具有所需值的表单字段插入到数据库表中。我会得到第一个&姓氏,电话和生日。地址信息永远不会进入数据库。我没有看到任何错误报告。

抱歉支持材料的长度......

模型

from django.contrib.auth.models import User
from django.db import models


class Profile(models.Model):
    class Meta:
        unique_together = [
            ("last_name", "first_name", "middle_name", "birthdate"),
        ]
        get_latest_by = "dateCreated"
        ordering = ['last_name', 'first_name', 'middle_name', 'birthdate']
        indexes = [
            models.Index(fields=['last_name', 'first_name']),
            models.Index(fields=['last_name'], name='last_name_idx'),
            models.Index(fields=['first_name'], name='first_name_idx'),
            models.Index(fields=['birthdate']),
        ]

    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        blank=False,
        null=False,
    )
    last_name = models.CharField(
        max_length=64,
        blank=False,
        null=False,
    )
    first_name = models.CharField(
        max_length=64,
        blank=False,
        null=False,
    )
    middle_name = models.CharField(
        max_length=64,
        blank=True,
        null=True,
    )
    birthdate = models.DateField(
        blank=False,
        null=False
    )
    Address1 = models.CharField(
        max_length=38,
        blank=False,
        null=False,
    )
    Address2 = models.CharField(
        max_length=38,
        blank=True,
        null=True,
    )
    City = models.CharField(
        max_length=15,
        blank=False,
        null=False,
    )
    State = models.CharField(
        max_length=2,
        blank=False,
        null=False,
    )
    Zip5 = models.CharField(
        max_length=5,
        blank=False,
        null=False,
    )
    Zip4 = models.CharField(
        max_length=4,
        blank=True,
        null=True,
    )
    phone = models.CharField(
        max_length=20,
        blank=False,
        null=False,
    )
    dateCreated = models.DateTimeField(
        auto_now_add=True,
        blank=False,
        null=False,
    )
    dateReviewed = models.DateTimeField(
        auto_now_add=True,
        blank=False,
        null=False,
    )

    def __str__(self):
        name = self.last_name + ", " + self.first_name

        if len(self.middle_name) > 0:
            name += " " + self.middle_name

        return name

表格

import datetime

from dateutil.relativedelta import relativedelta
from django import forms

from Members.models import Profile


class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['first_name','last_name','middle_name','birthdate','address1','address2','city',state','zip5','zip4','phone',]

    US_STATES = [
        ("AK", "AK"),
        ...
        ("WY", "WY"),
    ]

    first_name = forms.CharField(
        max_length=64,
        label='First Name',
        required=True
    )

    last_name = forms.CharField(
        max_length=64,
        label='Last Name',
        required=True
    )

    middle_name = forms.CharField(
        max_length=64,
        label='Middle',
        required=False,
        widget=(forms.TextInput(attrs={'placeholder': 'optional'}))
    )

    birthdate = forms.DateField(
        label='Birthdate',
        required=True,
        widget=(forms.TextInput(attrs={'placeholder': 'mm/dd/yyyy'}))
    )

    address1 = forms.CharField(
        max_length=38,
        label='Address1',
        required=True
    )

    address2 = forms.CharField(
        max_length=38,
        label='Address2',
        required=False,
        widget=(forms.TextInput(attrs={'placeholder': 'optional'}))
    )

    city = forms.CharField(
        max_length=15,
        label='City',
        required=True
    )

    state = forms.ChoiceField(
        label='State',
        required=True,
        widget=forms.Select,
        choices=US_STATES
    )

    zip5 = forms.CharField(
        max_length=5,
        label='Zip5',
        required=True
    )

    zip4 = forms.CharField(
        max_length=4,
        label='Zip4',
        required=False,
        widget=(forms.TextInput(attrs={'placeholder': 'optional'}))
    )

    phone = forms.CharField(
        max_length=20,
        label='Phone',
        required=True,
        widget=(forms.TextInput(attrs={'type': 'tel'}))
    )

    def signup(self, request, user):
        forms.Form.field_order = [
            'last_name','middle_name','birthdate','address1','address2','city','state','zip5','zip4','phone',]

        profile = user.Profile
        profile.first_name = self.cleaned_data['first_name']
        profile.last_name = self.cleaned_data['last_name']
        profile.middle_name = self.cleaned_data['middle_name']
        profile.birthdate = self.cleaned_data['birthdate']
        profile.Address1 = self.cleaned_data['address1']
        profile.Address2 = self.cleaned_data['address2']
        profile.City = self.cleaned_data['city']
        profile.State = self.cleaned_data['state']
        profile.Zip5 = self.cleaned_data['zip5']
        profile.Zip4 = self.cleaned_data['zip4']
        profile.phone = self.cleaned_data['phone']
        profile.save()

    def clean_birthdate(self):
        birthdate = self.cleaned_data['birthdate']

        eighteen_years_ago = datetime.date.today() - relativedelta(years=18)

        if birthdate > eighteen_years_ago:
            raise forms.ValidationError('Must be 18 or older', code='invalid')

        return birthdate

视图

from django.core.exceptions import *
from django.shortcuts import redirect
from django.shortcuts import render

from .forms import ProfileForm
from .models import Log
from .models import Profile


def add_new_profile(request):
    if request.method == 'POST':
        form = ProfileForm(request.POST)
        if form.is_valid():
            profile = form.save(commit=False)
            profile.user = request.user
            profile.save()
            my_render = render(request, 'Members/index.html')
        else:
            my_render = render(request, 'Members/index.html', {'profileForm': form})
    else:
        form = ProfileForm()
        my_render = render(request, 'Members/index.html', {'profileForm': form})

    return my_render


def index(request):
    Log.add("at top of Members.views")

    if not request.user.is_authenticated:
        return redirect('/accounts/login')

    try:
        profile = Profile.objects.get(user=request.user)
        my_render = render(request, 'Members/index.html')
    except ObjectDoesNotExist:
        my_render = add_new_profile(request)

    return my_render

1 个答案:

答案 0 :(得分:2)

在models.py

address1 = models.CharField(
        max_length=38,
        blank=False,
        null=False,
    )
    address2 = models.CharField(
        max_length=38,
        blank=True,
        null=True,
    )
    city = models.CharField(
        max_length=15,
        blank=False,
        null=False,
    )
    state = models.CharField(
        max_length=2,
        blank=False,
        null=False,
    )
    zip5 = models.CharField(
        max_length=5,
        blank=False,
        null=False,
    )
    zip4 = models.CharField(
        max_length=4,
        blank=True,
        null=True,

我认为它应该是小写的。 forms.py具有全部小写,如address1,address2,city,state,zip5和zip4。