Django,将排除的属性添加到提交的模型表单中

发布于 2024-11-04 13:42:04 字数 694 浏览 1 评论 0原文

我有一个模型表单,并且排除了两个字段:create_datecreated_by 字段。现在,我在使用 save() 方法时收到“Not Null”错误,因为 created_by 为空。

我尝试在 save() 方法之前将用户 ID 添加到表单,如下所示: form.cleaned_data['created_by'] = 1form .cleaned_data['created_by_id'] = 1。但这些都不起作用。

有人可以向我解释如何向提交的模型表单“添加”额外的内容以便保存吗?

class Location(models.Model):
    name = models.CharField(max_length = 100)
    created_by = models.ForeignKey(User)
    create_date = models.DateTimeField(auto_now=True)

class LocationForm(forms.ModelForm):
    class Meta:
        model = Location
        exclude = ('created_by', 'create_date', )

I've a modelform and I excluded two fields, the create_date and the created_by fields. Now I get the "Not Null" error when using the save() method because the created_by is empty.

I've tried to add the user id to the form before the save() method like this: form.cleaned_data['created_by'] = 1 and form.cleaned_data['created_by_id'] = 1. But none of this works.

Can someone explain to me how I can 'add' additional stuff to the submitted modelform so that it will save?

class Location(models.Model):
    name = models.CharField(max_length = 100)
    created_by = models.ForeignKey(User)
    create_date = models.DateTimeField(auto_now=True)

class LocationForm(forms.ModelForm):
    class Meta:
        model = Location
        exclude = ('created_by', 'create_date', )

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

何处潇湘 2024-11-11 13:42:04

由于您已在表单中排除了 created_bycreate_date 字段,因此尝试通过 form.cleaned_data 分配它们没有任何意义。

您可以执行以下操作:

如果您有视图,则只需使用 form.save(commit=False) ,然后设置 created_by 的值

def my_view(request):
    if request.method == "POST":
        form = LocationForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.created_by = request.user
            obj.save()
        ...
        ...

`

如果您是使用管理员,您可以覆盖 save_model() 方法来获得所需的结果。

class LocationAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.created_by = request.user
        obj.save()

Since you have excluded the fields created_by and create_date in your form, trying to assign them through form.cleaned_data does not make any sense.

Here is what you can do:

If you have a view, you can simply use form.save(commit=False) and then set the value of created_by

def my_view(request):
    if request.method == "POST":
        form = LocationForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.created_by = request.user
            obj.save()
        ...
        ...

`

If you are using the Admin, you can override the save_model() method to get the desired result.

class LocationAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.created_by = request.user
        obj.save()
九命猫 2024-11-11 13:42:04

将用户作为参数传递给构造函数,然后使用它来设置模型实例的created_by字段:

def add_location(request):
    ...
    form = LocationForm(user=request.user)
    ...

class LocationForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(forms.ModelForm, self).__init__(*args, **kwargs)
        self.instance.created_by = user

Pass a user as a parameter to form constructor, then use it to set created_by field of a model instance:

def add_location(request):
    ...
    form = LocationForm(user=request.user)
    ...

class LocationForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(forms.ModelForm, self).__init__(*args, **kwargs)
        self.instance.created_by = user
感情旳空白 2024-11-11 13:42:04

正确的解决方案是将带有预填充字段的对象实例传递给模型表单的构造函数。这样,这些字段将在验证时填充。如果需要字段,则在 form.save() 之后赋值可能会导致验证错误。

LocationForm(request.POST or None, instance=Location(
    created_by=request.user,
    create_date=datetime.now(),
))

请注意,instance 是一个未保存的对象,因此在 form 保存它之前不会分配 id。

The correct solution is to pass an instance of the object with pre-filled fields to the model form's constructor. That way the fields will be populated at validation time. Assigning values after form.save() may result in validation errors if fields are required.

LocationForm(request.POST or None, instance=Location(
    created_by=request.user,
    create_date=datetime.now(),
))

Notice that instance is an unsaved object, so the id will not be assigned until form saves it.

乞讨 2024-11-11 13:42:04

一种方法是使用 form.save(commit=False) (doc)

这将返回模型类的对象实例,而不将其提交到数据库。

因此,您的处理可能如下所示:

form = some_form(request.POST)
location = form.save(commit=False)
user = User(pk=1)
location.created_by = user
location.create_date = datetime.now()
location.save()

One way to do this is by using form.save(commit=False) (doc)

That will return an object instance of the model class without committing it to the database.

So, your processing might look something like this:

form = some_form(request.POST)
location = form.save(commit=False)
user = User(pk=1)
location.created_by = user
location.create_date = datetime.now()
location.save()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文