Django - ModelForm: Add a field not belonging to the model

2024/10/9 18:21:15

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 formsfrom crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, ButtonHolder, Submitfrom . import modelsclass DriftwoodForm(forms.ModelForm):class Meta:model = models.Driftwoodfields = ('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 imagefrom django.db import modelsclass TimeStampMixin(models.Model):class Meta:abstract = Truecreated = 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 methodencoded_image = models.TextField(blank=True, null=False, default='')
Answer

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

from django import formsfrom . import modelsclass DriftwoodForm(forms.ModelForm):class Meta:model = models.Driftwoodfields = ('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.

https://en.xdnf.cn/q/69991.html

Related Q&A

Row by row processing of a Dask DataFrame

I need to process a large file and to change some values.I would like to do something like that:for index, row in dataFrame.iterrows():foo = doSomeStuffWith(row)lol = doOtherStuffWith(row)dataFrame[col…

Tweepy Why did I receive AttributeError for search [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

Running qsub with anaconda environment

I have a program that usually runs inside a conda environmet in Linux, because I use it to manage my libraries, with this instructions:source activate my_environment python hello_world.pyHow can I run …

Flask Application was not able to create a URL adapter for request [duplicate]

This question already has answers here:Flask.url_for() error: Attempted to generate a URL without the application context being pushed(3 answers)Closed 10 months ago.I have this code which used to work…

Python typing deprecation

The latest typing docs has a lot of deprecation notices like the following: class typing.Deque(deque, MutableSequence[T]) A generic version of collections.deque.New in version 3.5.4.New in version 3.6.…

Cant install tensorflow with pip or anaconda

Does anyone know how to properly install tensorflow on Windows?Im currently using Python 3.7 (also tried with 3.6) and every time I get the same "Could not find a version that satisfies the requi…

send xml file to http using python

how can i send an xml file on my system to an http server using python standard library??

Why python Wnck window.activate(int(time.time()))

This to me is VERY strange. Could someone please explain why the activate() function should want a timestamp? Wouldnt 99.9% of the time be NOW or ASAP or "At your earliest convenience"? And…

Regex subsequence matching

Im using python but code in any language will do as well for this question.Suppose I have 2 strings. sequence =abcd string = axyzbdclkdIn the above example sequence is a subsequence of stringHow can I …

Read a Bytes image from Amazon Kinesis output in python

I used imageio.get_reader(BytesIO(a), ffmpeg) to load a bytes image and save it as normal image.But the below error throws when I read the image using imageio.get_reader(BytesIO(a), ffmpeg)Traceback …