2015-06-30 36 views
0

我正在寫什麼應該是一個非常簡單的待辦事項應用程序。問題是編輯視圖給我適合!我試圖用數據庫中的數據填充表單,但它只是沒有做正確的事情。我試過this page的信息,但是翻譯成基於類的視圖肯定已經打破了某些東西,或者我只是沒有使用正確的形式。如何使用Django中的數據庫中的值預填充表單?

下面是該模型的代碼:

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

您應該使用UpdateView,而不是FormView。這將照顧預先填寫你的表格。

另請注意,您不需要post方法中的任何邏輯 - 這一切都由通用視圖類來處理。

+0

魔法!謝謝。 – Jonathan

相關問題