Django - ModelForm:添加不属于模型的字段 [英] Django - ModelForm: Add a field not belonging to the model

查看:210
本文介绍了Django - ModelForm:添加不属于模型的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:对于我的表单,使用 django-crispy-forms 库。如果您有解决我的问题,涉及不使用 cripsy_forms 库,我接受一切。不想挑剔只需要一个解决方案/工作。感谢



在我的表单的 Meta 类中,我设置了模型, Driftwood ,它是我想要的形式的字段,但我也想添加另一个字段。一个不属于参考模型。我要添加的这个字段是一个图像。这个领域的原因是从它建立另一个模型。



我有一个名为的模型,图像有一些通过使用单个 models.ImageField()进行处理而填充的字段。这个图像也有一个 models.ForeginKey() Driftwood 模型。所以 Image 可以通过一个 Driftwood 的实例使用其关系集属性( floatingwood .image_set )。



view.py 我正在使用 generic.CreateView()作为将处理我的表单类的继承类。我打算使用 form_valid()方法通过 form.cleaned_data 获取我需要的图像。然后,我将创建图像,将我最近实例化的 Driftwood 中的 object.id 传递到我的图像模型。



我所知道的问题是不知道如何向Django的 FormModel 不属于与表单关联的模型。



forms.py



  from django import forms 

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout,ButtonHolder,Submit

从。导入模型

class DriftwoodForm(forms.ModelForm):
class Meta:
model = models.Driftwood
fields =('user','title','描述')

def __init __(self,* args,** kwargs):
super(DriftwoodForm,self).__ init __(* args,** kwargs)

self.helper = FormHelper()
self.helper.layout =布局(
'user',
'Insert Image Field Here',
'title',
'description',
ButtonHolder(
Submit('save','Save',css_class ='btn-success')




models.py



 从base64导入b64decode,b64encode#用于编码/解码图像

从django.db导入模型

class TimeStampMixin(models.Model):
class Meta:
abstract = True

created = models.Date TimeField(auto_now_add = True)
modified = models.DateTimeField(auto_now = True)


class Driftwood(TimeStampMixin):
user = models.ForeignKey(User)
title = models.CharField(max_length = 255)
description = models.TextField(max_length = 1000)
slug = models.SlugField(max_length = 255)


class Image(TimeStampMixin):

driftwood = models.ForeignKey(Driftwood)
image = models.ImageField(upload_to ='static / images')

#被编码为保存方法中的字符串
encoded_image = models.TextField(blank = True,null = False,default ='')


解决方案

这是一个非django-crispy形式的表单:


$ b来自django的$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $导入模型


class DriftwoodForm(forms.ModelForm):
class Meta:
model = models.Driftwood
fields =('user',' title','description','image')

image = forms.ImageField()

完整的文档: https:// docs.djangoproject.com/en/1.8/ref/forms/fields/#django.forms.ImageField






现在你要做的只是像往常一样使用表单,调用 save()在表单上不会尝试将图像保存到模型中在 Meta 类中指定,但您可以使用该字段进行任何所需。



我不确定你,但我想你可以用django-crispy-forms来做同样的事情,只需添加下面的字段,并从模型本身来假设它。


Note: Using django-crispy-forms library for my form. If you have a solution to my problem that involves not using the cripsy_forms library, I accept it all the same. Not trying to be picky just need a solution / work around. Thanks

In my form's Meta class I set the model, Driftwood, and it's fields I want to in the form, but I also want to add another field. One that does not belong the the referenced model. This field I want to add is an image. The reason for this field is to build another model from it.

I have a model named Image that has some fields that get populated by doing things with a single models.ImageField(). This Image also has a models.ForeginKey() with a relation to the Driftwood model. So Image can be accessed through an instance of a Driftwood using its relational set property (driftwood.image_set).

In view.py I am using generic.CreateView() as the inherited class that will handle my form class. I plan on using the form_valid() method to acquire through form.cleaned_data, the image that I need. I will then create the image, passing the object.id of my newly instantiated Driftwood and the image into my Image model.

The problem I have though is not knowing how to add a custom field to Django's FormModel that does not belong to the model associated with the form.

forms.py

from django import forms

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, ButtonHolder, Submit

from . import models

class DriftwoodForm(forms.ModelForm):
    class Meta:
        model = models.Driftwood
        fields = ('user', 'title', 'description')

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

        self.helper = FormHelper()
        self.helper.layout = Layout(
            'user',
            'Insert Image Field Here',
            'title',
            'description',
            ButtonHolder(
                Submit('save', 'Save', css_class='btn-success')
            )
        )

models.py

from base64 import b64decode, b64encode # used to encode/decode image

from django.db import models

class TimeStampMixin(models.Model):
    class Meta:
        abstract = True

    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)


class Driftwood(TimeStampMixin):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=255)
    description = models.TextField(max_length=1000)
    slug = models.SlugField(max_length=255)


class Image(TimeStampMixin):

    driftwood = models.ForeignKey(Driftwood)
    image = models.ImageField(upload_to='static/images')

    # gets encoded as a string in the save method
    encoded_image = models.TextField(blank=True, null=False, default='')

解决方案

This is how you do it to a non django-crispy-forms form:

from django import forms

from . import models


class DriftwoodForm(forms.ModelForm):
    class Meta:
        model = models.Driftwood
        fields = ('user', 'title', 'description', 'image')

    image = forms.ImageField()

full documentation: https://docs.djangoproject.com/en/1.8/ref/forms/fields/#django.forms.ImageField


Now what you have to do is simply use the form as you always do, calling save() on the form won't try to brute save the image to the model specified in the Meta class, but you will be able to do whatever you want with the field.

I'm not sure thou, but i suppose you can do the same with django-crispy-forms, just add the field below and suppose its from the model itself.

这篇关于Django - ModelForm:添加不属于模型的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆