2017-03-07 54 views
0

在我的previous問題,我最近問如何在HTML中使用Django 1.9顯示forms.py。現在,這是完成即時通訊嘗試做一個按鈕,當選擇已經完成(在這種情況下它是單選按鈕),它會發布到數據庫,並繼續問問題。如何保存到數據庫點擊

目前我試圖讓它在我的views.py中發佈,但即時通訊沒有讓它發送數據的運氣。

def question1(request): 
    question_form = QuestionForm() 
    if request.method == 'POST': 
     form = QuestionForm(request.POST) 
     if form.is_valid(): 
      return render(request, 'music.questions2,html') 
    return render(request, 'music/question1.html', locals()) 

會真的很感謝幫助做到這一點。

+0

難道真的單選按鈕或多個按鈕?記住:單選按鈕允許用戶選擇** ONY一個**,而多個允許... **多個**選項! –

+0

@nik_m是的,我看到你有複選框給你的解決方案,但Radiobutton更適合我的需求。 (不要從我的查詢中獲得幫助) –

+0

好!沒問題!正如下面的答案一樣,使用['form.save()'](https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#the-save-method)。它意味着從'ModelForm'有一個'form'繼承,所以它與一個Model關聯。否則,Django將無法保存數據,因爲它不知道「連接」。 –

回答

1
def question1(request): 
    question_form = QuestionForm() 
    if request.method == 'POST': 
     form = QuestionForm(request.POST) 
      if form.is_valid(): 
       form.save() # save to db! 
       return render(request, 'music.questions2,html') 
    return render(request, 'music/question1.html', locals()) 

# models.py 
class Question(models.Model): 
    # Q_CHOICES is the previous declared one 
    question = models.CharField(max_length=20, choices=Q_CHOICES) 

# forms.py 
class QuestionForm(forms.ModelForm): 
     class Meta: 
      model = Question 
      fields = ['question'] 
      widgets = { 
       'question': forms.RadioSelect() 
      } 
1

用途:form.save()

def question1(request): 
    if request.method == 'POST': 
     form = QuestionForm(request.POST) 
     if form.is_valid(): 
      form.save() 
      return render(request, 'music.questions2,html') 
    else: 
     form = QuestionForm() 
    return render(request, 'music/question1.html', locals())