是什么原因导致我的输入未保存到Django模型数据库中?

时间:2019-05-21 18:21:37

标签: python django

我正在尝试使用Django创建测验网站。我创建了一个模型窗体,其中输入框与提交按钮一起出现在网站上。根据cmd的说法,在其中输入文本并提交文本效果很好,并且还发送POST请求。但是,这似乎并没有将输入保存到模型中,而这正是我要实现的目标。

views.py

NoFileFoundException

forms.py

from django.http import HttpResponse
from django.shortcuts import render, redirect

from .models import Question, InputText
from .forms import AnswerForm

# Only shows relevant view

def kvizpost(request):
    if request.method == 'POST':
        form = AnswerForm(request.POST)
        if form.is_valid():
            text = form.cleaned_data()
            text.save()
            return redirect('kviz:kviz')

    else:
        form = AnswerForm()
    return render(request, 'vprasanja/kviz.html', {'form' : form})

models.py

from django import forms
from kvizapp.models import InputText

class AnswerForm(forms.ModelForm):
    class Meta:
        model = InputText
        fields = ('vnesi',)

kviz.html

from django.db import models

# Only shows relevant model

class InputText(models.Model):
    vnesi = models.CharField(max_length=100)

编辑:要求我显示URL。


{% block body %}
<form action = "/kviz/" method="post">
{% csrf_token %}
{{ form.as_p }}
<br>
<input type="submit" value="Vnos">
</form>
{% endblock %}

2 个答案:

答案 0 :(得分:0)

if form.is_valid():
    form.save()
    return redirect('kviz:kviz')
else:
    # if form is not valid
    return render(request, 'vprasanja/kviz.html', {'form' : form})

在表单实例上使用 save()方法保存表单,因为您正在使用 ModelForm ,所以一切正常。

引用:https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/#the-save-method

答案 1 :(得分:0)

  

forms.py

  class Meta:
        model = InputText
        fields = ['vnesi']
  

views.py

def kvizpost(request):
    if request.method == 'POST':
        form = AnswerForm(request.POST)
        if form.is_valid():
            vnesi = form.cleaned_data['vnesi']
            text = form.save(commit=False)
            text.vnesi = vnesi
            text.save()
            return redirect('kviz:kviz')
         Or You Can simply do this 
          if form.is_valid():             
            text = form.save(commit=False)
            text.save()
            return redirect('kviz:kviz')

    else:
        form = AnswerForm()
    return render(request, 'vprasanja/kviz.html', {'form' : form})