English 中文(简体)
Django 更新一个使用模型的领域 表格
原标题:Django update one field using ModelForm

www.un.org/Depts/DGACM/index_spanish.htm 如果POST要求只有一个领域作为参数,那么在使用模拟表格的情况下,我如何更新一个领域? 模型现场试图压倒在POST申请中未通过但无结果导致数据损失的领域。

我的模型是+25领域。

class C(models.Model):
    a = models.CharField(max_length=128)
    b = models.CharField(max_length=128)
    ...
    x = models.IntegerField()

并且我有一份桌面应用程序,该台式应用系统的确要求,以便通过一种暴露的浏览器法对C的照相。 y

在复印方法中,我正在使用模拟表格对以下领域进行验证:

form = CModelForm(request.POST, instance=c_instance)
if form.is_valid():
    form.save() 

除(a)项所述外,还有些抱怨说,其他一些领域不能完全无效,或者(如果所有领域都是任择的)超出它们。

有些人知道如何管理? 我将进行人工检查和人工更新,但模型的实地清单如此之长......

最佳回答

您可使用您的《示范公约》中的一系列领域。 形式如下:

class PartialAuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ( name ,  title )

From the docs:

If you specify fields or exclude when creating a form with ModelForm, then the fields that are not in the resulting form will not be set by the form s save() method.

https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-a-subset-of-on-the-form

问题回答

这一数字。 我所做的是更新这一请求。 POST 字典,其数值来自具体情况,因此所有未改变的田地都自动存在。 这将:

from django.forms.models import model_to_dict
from copy import copy

def UPOST(post, obj):
       Updates request s POST dictionary with values from object, for update purposes   
    post = copy(post)
    for k,v in model_to_dict(obj).iteritems():
        if k not in post: post[k] = v
    return post

之后,你刚刚做到:

form = CModelForm(UPOST(request.POST,c_instance),instance=c_instance)

我知道,我很晚才知道该党,但你可以为此创造工厂功能。

def model_form_factory(cls, data, *args, **kwargs):
    """ Create a form to validate just the fields passed in the data dictionary.

    e.g. form = form_factory(MyModel, request.POST, ...)

    """


    data = data.copy()
    data.pop( csrfmiddlewaretoken , None)

    class PartialForm(forms.ModelForm):
        class Meta:
            model  = cls
            fields = data.keys()

    return PartialForm(data, *args, **kwargs)

我解决了类似罗马Semko的答复(可能无法与许多Tomany油田合作):

表格_init__ 更新数据的方法:

import urllib

from django import forms
from django.http import QueryDict
from django.forms.models import model_to_dict

class MyModelForm (forms.ModelForm):
    class Meta:
        model = MyModel

    def __init__ (self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)

        # if form has being submitted and 
        # model instance exists, then get data

        if self.is_bound and self.instance.pk:

            # get current model values
            modeldict = model_to_dict( instance )
            modeldict.update( self.data.dict() )

            # add instance values to data
            urlencoded = urllib.urlencode( modeldict )
            self.data = QueryDict( urlencoded )

确实,你必须制定方法,在你的要求中没有数据,例如:

class MyModel(Model):
    ... your model ...

    def initial(self,data):
        fields = [list of possible fields here]

        for field in fields:
            if data.get(field) is None:
                data[field] = getattr(self,field)

        return data

之后,通过这些数据的形式如下:

form = MyForm(instance.initial(request.POST.copy()),instance=instance)

for JSON:

from json import loads

form = MyForm(instance.initial(loads(request.body)),instance=instance)




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签