2017-08-25 58 views
0

我在django中有一個項目,我創建了一個簡單的窗體,允許用戶創建一個簡單的窗體,要求輸入姓名和出生日期和位置。我收到出生日期的關鍵錯誤部分,我不知道爲什麼。窗體的關鍵錯誤 - DJANGO

我想收集數據並將其存儲,然後將其添加到數據庫記錄。

以下是意見文件:

cd = form.cleaned_data 
first_name = cd['first_name'] 
last_name = cd['last_name'] 
dob_month = cd['dob_month'] 
dob_day = ['dob_day'] 
dob_year = ['dob_year'] 
city = cd['city'] 
state = cd['state'] 
phone = cd['phone'] 
privacy = cd['privacy'] 

這裏是模型文件:

user = models.ForeignKey(User, on_delete=models.CASCADE) # server 
first_name = models.CharField(max_length=25, default='first') 
last_name = models.CharField(max_length=25, default='last') 
dob_month = models.IntegerField(default=0) 
dob_day = models.IntegerField(default=0) 
dob_year = models.IntegerField(default=0) 
city = models.CharField(max_length=45) # user 
state = models.CharField(max_length=25, default='state') 
phone = models.BigIntegerField(default=0) # user 
privacy = models.SmallIntegerField(default=1) # user 
created = models.DateTimeField(auto_now_add=True) # server 

這裏是表單文件:

class ProfileForm(forms.ModelForm): 
    split_choices = (('1', 'public'), 
        ('2', 'private')) 
    privacy = forms.TypedChoiceField(
     choices=split_choices, widget=forms.RadioSelect, coerce=int 
    ) 
    dob = forms.DateField(widget=extras.SelectDateWidget) 
    class Meta: 
     model = Profile 
     fields = ['first_name', 'last_name', 'dob', 'city', 'state', 'phone', 'privacy'] 

最後,這裏是錯誤我得到:

KeyError at /setup_profile/ 
    'dob_month' 
    Request Method: POST 
    Request URL: http://127.0.0.1:8000/setup_profile/ 
    Django Version: 1.8.6 
    Exception Type: KeyError 
    Exception Value:  
    'dob_month' 
    Exception Location: C:\Users\OmarJandali\Desktop\opentab\opentab\tab\views.py in profile_setup, line 292 
first_name 'omar' 
last_name 'jandali' 
dob_month '1' 
dob_day  '23' 
dob_year '2024' 
city  'riverside' 
state  'ca' 
phone  '9515343666' 
privacy  '1' 
submit  'submit' 

更新:

這裏是views.py文件,但問題是與CD [「dobv_month」],但我不知道爲什麼錯誤是從那裏來。

def profile_setup(request): 
    if 'username' not in request.session: 
     return redirect('login') 
    else: 
     # the following is just going to grab the currently logged in user and 
     # save the profile information to the appropriate user 
     username = request.session['username'] 
     currentUser = User.objects.get(username = username) 
     # the following is the provessing for the form where the user entered 
     # the profile informaiton 
     if request.method == 'POST': 
      form = ProfileForm(request.POST) 
      if form.is_valid(): 
       cd = form.cleaned_data 
       first_name = cd['first_name'] 
       last_name = cd['last_name'] 
       dob_month = cd['dob_month'] 
       dob_day = ['dob_day'] 
       dob_year = ['dob_year'] 
       city = cd['city'] 
       state = cd['state'] 
       phone = cd['phone'] 
       privacy = cd['privacy'] 
       # this is the new record that is going to be created and saved 
       new_profile = Profile.objects.create(
        user = currentUser, 
        first_name = first_name, 
        last_name = last_name, 
        dob_month = dob_month, 
        dob_day = dob_day, 
        dob_year = dob_year, 
        city = city, 
        state = state, 
        phone = phone, 
        privacy = privacy, 
       ) 
       return redirect('home_page') 
     else: 
      # this is what is going to be saved into the html file and used to 
      # render the file 
      form = ProfileForm() 
      message = 'fill out form below' 
      parameters = { 
       'form':form, 
       'currentUser':currentUser, 
       'message':message, 
      } 
      return render(request, 'tabs/profile_setup.html', parameters) 
+0

使用的ModelForm,而不是正常的form.use DateTimeField字段爲formfields dob_month,dob_day,dob_year –

+0

我不知道究竟你在說什麼..我應該在哪裏進行切換的ModelForm代替form.use的.. @EmilGeorgeJames –

+0

你可以發佈你的整個視圖文件嗎? –

回答

1

假設您的型號名稱爲User

forms.py

from .models import User 
class UserForm(forms.ModelForm): 


    def __init__(self, *args, **kwargs): 
     super(UserForm, self).__init__(*args, **kwargs) 

    class Meta: 
     model = User 
     fields = '__all__' 

views.py

def user_create(request): 
    form = UserForm(request.POST or None) 
    if request.method == 'POST': 
     form = UserForm(request.POST or None) 
     if not form.is_valid(): 
      print form.errors 
      return render(request, 'user_create.html', {'form': form}) 
     else: 
      first_name = form.cleaned_data.get("first_name") 
      last_name = form.cleaned_data.get("last_name") 
      # pass your extra fields here 
      new_user = User.objects.create_user(
       user=user, 
       first_name=first_name, 
       last_name=last_name, 
       ) 
      new_user.save() 
      return redirect('where you want to redirect',)  
    return TemplateResponse(request, 'user_create.html') 

最終用戶將被保存。

閱讀文檔:https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/

+0

問題不與名字和姓氏,它是dob_month,dob_day,dob_year ....我認爲這個問題在配置文件的forms.py文件中... –

+0

順便說一句。它工作,我必須使用'form.cleaned_data.get(「dob _...)'。謝謝埃米爾... @EmilGeorgeJames –