如何在Django中使用数据库中的值预填充表单?

时间:2015-06-30 21:19:34

标签: python django django-forms

我正在写一个应该是一个非常简单的待办事项应用程序。问题是编辑视图给了我适合!我正在尝试使用数据库中的数据填充表单,而这只是做得不对。我已经尝试了this page中的信息,但是基于类的视图的翻译必定会破坏某些内容,或者我只是没有使用正确的表单。

以下是模型的代码:

class Todo(models.Model):
    id = models.AutoField(primary_key=True)
    todo = models.CharField(max_length=255, unique=True)
    todo_detail = models.TextField(default='')
    date_created = models.DateField(default=timezone.now())
    estimated_completion = models.DateTimeField(default=timezone.now())
    maybe_completed = models.BooleanField("Completed?", default=False)

    def __unicode__(self):
        return self.todo

视图代码,注释掉的位来自链接:

class TodoEditView(FormView):
    model = Todo
    form_class = TodoEditForm
    template_name = 'todo_edit.html'

    #def get(self, request, *args, **kwargs):
    #    form = self.form_class()
    #    form.fields['todo'].queryset = Todo.objects.get(id=self.kwargs['pk'])
    #    form.fields['todo_detail'].queryset = Todo.objects.get(
    #        id=self.kwargs['pk'])
    #    form.fields['date_created'].queryset = Todo.objects.get(
    #        id=self.kwargs['pk'])
    #    form.fields['estimated_completion'].queryset = Todo.objects.get(
    #        id=self.kwargs['pk'])
    #    form.fields['maybe_completed'].queryset = Todo.objects.get(
    #        id=self.kwargs['pk'])
    #    template_vars = RequestContext(request, {
    #        'form': form
    #        })
    #    return render_to_response(self.template_name, template_vars)

    def get_context_data(self, **kwargs):
        context = super(TodoEditView, self).get_context_data(**kwargs)
        context['todo'] = Todo.objects.get(id=self.kwargs['pk'])
        return context

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            todo = request.POST['todo']
            todo_detail = request.POST['todo_detail']
            estimated_completion = request.POST['estimated_completion']
            date_created = request.POST['date_created']
            t = Todo(todo=todo, todo_detail=todo_detail,
                     estimated_completion=estimated_completion,
                     date_created=date_created)
            t.save()
            return redirect('home')

表单代码:

class TodoEditForm(forms.ModelForm):

    class Meta:
        model = Todo
        exclude = ('id', )

模板代码:

{% extends 'todos.html'%}
{% block content %}
<form method="post" action="{% url 'add' %}">
<ul>
    {{ form.as_ul }}
    {% csrf_token %}
</ul>
{{todo.todo}}

</form>
{% endblock %}

我到底做错了什么?

1 个答案:

答案 0 :(得分:1)

您应该使用UpdateView,而不是FormView。这将预先填写您的表格。

另请注意,您不需要post方法中的任何逻辑 - 通用视图类都会处理这些逻辑。