Comments (4)
Okay, everything is clear now. I will provide a way to pass extra arguments to the callable in the next release. Probably introduce a new attribute called schema_kwargs
. Something like this:
# declare extra arguments to pass to the callable schema
self.fields['some_json'].widget.schema_kwargs = {'key': value, ...}
Meanwhile, let me suggest a simpler hack for your use case.
The widget doesn't care what the value of the instance
attribute is. You can set it to whatever value you want and it will be passed to the callable, i.e. you can treat it as a vehicle to carry any kind of data:
# form
class MyModelForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["some_json"].widget.instance = {
'instance': self.instance,
'some_property': kwargs['initial']['some_property']
}
# callable
def callable_config_schema(data):
"""
data is a dict containing these keys:
- instance: instance of the model
- some_property: value of some_property field
""""
if data['instance'] is not None:
# model instance is present
...
else:
# no instance found, so use data['some_property'] value
...
from django-jsonform.
Hi, I think I kind of understand what you're proposing.
But if you could also provide a minimal example of the model and your callable schema function, it will be a bit clearer to me.
from django-jsonform.
Hello,
I've given a more complete example below, alongside my current (hacky) solution. I hope this clarifies things.
def schema_getter(some_property):
# .... <fetches schema based on value of `some_property`>
# Model
class MyModel(models.Model):
some_property = models.CharField(max_length=128)
def callable_config_schema(model_instance=None):
# Here it would be great to be able to know what the initial value of
# `some_property` is, as the model instance hasn't been instantiated yet
# for CreateView
if model_instance: return schema_getter(model_instance.some_property)
some_json = JSONField(schema=callable_config_schema)
# Form
class MyModelForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# This is my hack to make sure the schema is correctly selected
if kwargs.get("initial", {}).get("some_property"):
self.fields["some_json"].widget.schema = self.fields[
"some_json"
].widget.schema(MyModel(integration_id=kwargs["initial"]["some_property"]))
# manually set the current instance on the widget
# see https://django-jsonform.readthedocs.io/en/latest/fields-and-widgets.html#accessing-model-instance-in-callable-schema
self.fields["some_json"].widget.instance = self.instance
class Meta:
model = MyModel
fields = "__all__"
# View
class MyCreateView(CreateView):
model = MyModel
form_class = MyModelForm
def get_initial(self):
# self.kwargs contains parameters from the url
return {'some_property': self.kwargs['some_property']}
In urls.py:
urlpatterns = [
path(
"some/path/<some_property>/",
views.MyCreateView.as_view()
),
....
from django-jsonform.
Good idea - thanks!
from django-jsonform.
Related Issues (20)
- New release HOT 1
- Custom validation of object properties not showing error next to field HOT 2
- Form dynamics not working after reloading django-jsonform with HTMX HOT 3
- Using an object with empty Properties, having all properties inside AdditionalProperties HOT 3
- Setting JSONField schema dynamically HOT 3
- Copy-pasting / Duplications for Array items and Objects
- Horizontal display of properties HOT 1
- Dynamic header generation for array items HOT 2
- Customising "Add key" and "Add item" texts HOT 1
- Add button to open link in URLField HOT 5
- Decimal values not allowed when entering integer minimum and maximum for 'number' types HOT 4
- Define defaults for an array HOT 3
- Subfields in ArrayField should get the relevant input type
- Issue with errors for fields inside an anyOf schema not displaying correctly HOT 4
- validators for jsonfield are not updated with dynamic schema HOT 3
- Cooperation with other repository `django-pydantic-field` for model schema validation HOT 2
- Title is not populated for `oneOf` when referenced through `$ref` HOT 5
- tests dir in .venv broke project tests HOT 2
- JSONFieldWidget attrs HOT 1
- Bug: Nullable Subschema (anyOf with `null`) causes UI exception
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from django-jsonform.