django视图在模板中显示模型表单

时间:2013-12-30 14:09:21

标签: python django

我已经创建了一个模型表单。我想在网页上显示它并将表单数据推送到数据库中:下面是模型和视图。这里应该由db自动生成topic_id和command_id。如果我创建的视图是正确的,请告诉我。

谢谢, 阿伦

models.py

from django.db import models
# Create your models here.
from django.forms import ModelForm

class Topics(models.Model):
    topic_id = models.AutoField(primary_key=True)
    topic_name = models.CharField(max_length=200)
    def _unicode_(self):
        return self.name

class Command(models.Model):
    command_id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=200)
    command = models.CharField(max_length=200)
    description=models.CharField(max_length=200)
    topic_under=models.ForeignKey(Topics)
    def _unicode_(self):
        return self.name

class TopicsForm(ModelForm):
    class Meta:
        model = Topics

class CommandForm(ModelForm):
    class Meta:
        model = Command

views.py

# Create your views here.
from command.models import Command
from command.models import CommandForm
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.core.context_processors import csrf

def submitform(request):
    if request.method == "POST":
        form = CommandForm()
        if form.is_valid():
           form.save()
           return render(request, 'newcommand.html')
    else:
        form = CommandForm()
        return render(request, 'inputtest.html', {'form': form})

1 个答案:

答案 0 :(得分:3)

在以下块中:

form = CommandForm()
if form.is_valid():
   form.save()
   return render(request, 'newcommand.html')

form = CommandForm()替换为form = CommandForm(request.POST)

这将解决它。 无论如何,你应该尝试基于通用类的视图,因为它们更强大和标准。 您可以了解他们here。 看一下ListView,CreateView,UpdateView和DeleteView(a.k.a.CRUD)