Django Admin添加表单并操纵模型数据

时间:2014-07-18 16:59:19

标签: django django-forms django-admin

我有一个ModelAdmin,我希望将自定义表单添加到:

class PlaceAdminForm(forms.ModelForm):
    lat = forms.DecimalField()
    lon = forms.DecimalField()

    class Meta:
        model = Place

class PlaceAdmin(admin.ModelAdmin):
    search_fields = ["name"]
    form = PlaceAdminForm

    def save_model(self, request, obj, form, change):
        obj.gps_location = Point(self.form.lat, self.form.lon)
        obj.save(request)
admin.site.register(Place, PlaceAdmin)

当我运行服务器并尝试添加Place时,我收到错误:type object 'PlaceAdminForm' has no attribute 'lat'

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

与任何Django表单一样,您可以从cleaned_data字典中获取经过验证的数据。

Point(form.cleaned_data['lat'], form.cleaned_data['lon'])