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

How to initialise data on a non model form?

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

我要做的是从使用 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 的新手并且一直在学习,我有不知道我做错了什么或我应该看哪里。

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

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

访问 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): """ Returns 用于此视图上的表单的初始数据。 """ initial = super(DepartmentFormView, self).get_initial(**kwargs)

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

    return initial