从模板上传到Django DataBase

时间:2013-07-26 14:50:32

标签: html django forms twitter-bootstrap

我正在尝试创建一个网页,您可以将问题上传到Questions数据库。我想知道Django有没有简单的方法呢?我可以上传它,以便可以从Django管理员访问吗?这就是我所拥有的。

#Models
class Question(models.Model):
question = models.CharField(max_length=400)
answer = models.CharField(max_length=400)
def __unicode__(self):
    return self.question + "?"

class QuestionForm(ModelForm):
    class Meta:
        model = Question
        fields = ['question', 'answer']

#Question Template
<div class="container" align="center">
  <div class="hero-unit3" align="center">
      <h3>
        Feel free to post some questions, and a DarKnight representative will answer them for you.
      </h3>
    </div>
  </div>
</div>
<div class="row">
  <div class="span6">
    <h4>
      <form action="<!-- NO IDEA WHAT TO DO -->" method="post">
        <input type="text" name="question" />
  </div>
</div>
</div>

#views.py
class question(generic.ListView):
    template_name = 'users/question.html'
    context_object_name = 'Question_list'
    def get_queryset(self):
        return Question.objects.order_by('question')

2 个答案:

答案 0 :(得分:1)

实现所需目标的最简单方法是使用CreateView

在views.py中:

from django.views.generic.edit import CreateView
from yourapp.models import Question

class QuestionCreate(CreateView):
    model = Question
    fields = ['question', 'answer']

创建新模板名称question_form.html

<form action="" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Create" />
</form>

希望它有所帮助!

答案 1 :(得分:0)

要为django admin提供模型,您必须通过

将模型注册到admin
from django.contrib import admin

class Question(models.Model):
...

admin.site.register(Question)

另外,要从自定义模板执行此操作,您可以使用model form

表单可以作为表格或段落显示在模板中。

假设您将表单作为f呈现给模板,请在模板中使用它,如下所示

<form action='..' method='post'>
{{ f.as_t }} //or f.as_p for paragraph
</form>