Django: MultiValueField and MultiWidget

The Django documentation does not provide a very detailed explanation of how to use MultiValueField and MultiWidget. I tried to analyze one implementation and did not have good results. Will someone mind give me a quick pointer in the right direction?

My example:

widgets.py

from django import forms class TestMultiWidget(forms.MultiWidget): def __init__(self, attrs=None): widgets = ( forms.TextInput(attrs=attrs), forms.TextInput(attrs=attrs), ) super(TestMultiWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: return value.split(':::')[0:2] return ['', ''] 

fields.py

 from django import forms from widgets import TestMultiWidget class TestMultiField(forms.MultiValueField): widget = TestMultiWidget def __init__(self, *args, **kwargs): fields = ( forms.CharField(), forms.CharField(), ) super(TestMultiField, self).__init__(fields, *args, **kwargs) def compress(self, data_list): if data_list: return ':::'.join(data_list) return '' 

models.py

 from django.db import models from util.fields import TestMultiField class Test(models.Model): a = models.CharField(max_length=128) b = TestMultiField() c = models.CharField(max_length=128) 

admin.py

 from django.contrib import admin from models import Test admin.site.register(Test) 

And the administrator received .

Does anyone know what is going on here? I assume there is some unintended exception exception, but I could not find the source.

Thanks!

+6
source share
1 answer

Note that django.forms.MultiValueField is a form field , not a model (e.g. django.db.models.CharField). Therefore, it is not considered as a model field in your test model and was not created in your database. (You can check it with ./manage.py sqlall myapp ).

Change your models.py to:

 from django.db import models from fields import TestMultiField class TestMultiModelField(models.Field): def formfield(self, **kwargs): defaults = {'form_class': TestMultiField} defaults.update(kwargs) return super(TestMultiModelField, self).formfield(**defaults) def get_internal_type(self): return 'TextField' class Test(models.Model): a = models.CharField(max_length=128) b = TestMultiModelField() c = models.CharField(max_length=128) 

cancel the table (on linux / mac: ./manage.py sqlclear myapp | ./manage.py dbshell ) and syncdb to create your own table, this time with column b. Check your administrator now.

Explanation: To create a custom model field, follow these steps: https://docs.djangoproject.com/en/dev/howto/custom-model-fields/

Set the model field corresponding to the form , the formfield method was used.

(BTW, the β€œRight” way to create a model field is probably a little different using to_python and get_prep_value)

+15
source

Source: https://habr.com/ru/post/888582/


All Articles