如何在非模型表单上初始化数据?

时间:2015-01-29 09:31:41

标签: python django forms django-forms formview

关于不使用Model对象的表单/视图,我有一个小问题。我似乎已经按照应有的方式设置了它,但我似乎无法弄清楚如何传递数据以初始化我的编辑表单中的字段。

我要做的是从使用Delphi开发的REST服务器获取数据。所以这个django thingie将不会使用正常的django ORM模型。目前我有它的工作,所以我的应用程序显示了使用REST调用服务器获得的离线列表。每个部门都将其ID作为超链接。

我想要做的下一步/事情是显示一个表单,用户可以在其中编辑所选部门的某些值。从逻辑上讲,一切似乎都应该以它应该的方式连接在一起(据我所见)。可悲的是......无论出于什么原因......我似乎无法将有关所点击的ID甚至列表中所选对象的信息传递给详细视图。

有人能帮助我吗?这就是我到目前为止所做的:

urls.py:

# DelphiClient/urls.py
from django.conf.urls import patterns
from django.conf.urls import url

from . import views

urlpatterns = patterns("",
    url(
        regex=r"^Departments$",
        view=views.DelphiDepartmentsListView.as_view(),
        name="Departments"
    ),
    url(
        regex=r'^Department/(?P<pk>\d+)/$', 
        view=views.DepartmentFormView.as_view(), 
        name='department_update'
    ),
)

views.py:

# DelphiClient/views.py

...

from .client import DelphiClient
from .forms  import DepartmentForm

class DelphiDepartmentsListView(TemplateView):
    template_name = 'DelphiDepartmentList.html'

    def get_context_data(self, **kwargs):
        client = DelphiClient()
        departments = client.get_department()

        context = super(DelphiDepartmentsListView, self).get_context_data(**kwargs)
        context['departments'] = departments

        #client.update_department(1, 'Update From Django')
        return context

class DepartmentFormView(FormView):
    template_name = 'DepartmentUpdate.html'
    form_class = DepartmentForm
    success_url = '/DelphiClient/Departments'

    def get_initial(self, **kwargs):
        """
        Returns the initial data to use for forms on this view.
        """
        initial = super(DepartmentFormView, self).get_initial(**kwargs)

        # How can I get the ID passed along from the list view
        # so I can get the correct object from my REST server and
        # pass it along in the Initial ???

        return initial

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        # It should return an HttpResponse.
        print "form.data {0}".format(form.data)
        client = DelphiClient()
        client.update_department(form.data["flddepartmentId"],form.data["flddepartmenet"])

        return super(DepartmentFormView, self).form_valid(form)    

forms.py:

# DelphiClient/forms.py

from django import forms
from .client import DelphiClient


class DepartmentForm(forms.Form):
    # How can I fill in the values for these fields using an object passed in
    # thhrough Initial or the context?

    flddepartmentId = forms.IntegerField(label="Department ID") #, value=1)
    flddepartmenet   = forms.CharField(label="New Description", max_length=100)    

    def update_department(self, *args, **kwargs):
        #print "update_department"
        #print self.data        
        #print self.data["flddepartmenet"]
        client = DelphiClient()
        client.update_department(self.data["flddepartmentId"],self.data["flddepartmenet"])

表格的模板:

<h1>Update Department</h1>
<p>Update Department? {{ department.flddepartmentid }}</p>
<p>Something : {{ something }}</p>

<form action="" method="post">
     {% csrf_token %}
     {{ form.as_p }}

     <p><label for="id_flddepartmentId">Department ID:</label> <input id="id_flddepartmentId" name="flddepartmentId" type="number" value="1"></p>
<p><label for="id_flddepartmenet">New Description:</label> <input id="id_flddepartmenet" maxlength="100" name="flddepartmenet" type="text"></p>

    <input type="submit" value="OK">
</form>        

正如你所看到的......我很接近......但是还没有雪茄:-)因为我是Python / Django的新手,并且一直在学习,我不知道我在做什么做错了或我应该看看。

如果有人能够帮助或指出我正确的方向,那将非常感激。

1 个答案:

答案 0 :(得分:1)

位置和基于名称的参数分别存储在self.argsself.kwargs中(see the docs基于名称的过滤)。因此,您可以使用pk访问self.kwargs['pk']

我不确定您是否应在表单中包含flddepartmentId作为可编辑字段。这意味着用户可以转到/Department/1/,但在提交表单时输入flddepartmentId=2。从表单中删除字段可能更好,然后在调用update_department时使用URL中的值。

client.update_department(self.kwargs['pk'],self.data["flddepartmenet"])

如果您确定要在表单中加入flddepartmentId,那么您的get_initial方法应如下所示:     def get_initial(self,** kwargs):         &#34;&#34;&#34;         返回此视图上用于表单的初始数据。         &#34;&#34;&#34;         initial = super(DepartmentFormView,self).get_initial(** kwargs)

    initial['flddepartmentId'] = self.kwargs['pk']

    return initial