django models.commaseparatedintegerfield with forms.checkboxselectmultiple widget

  • Last Update :
  • Techknowledgy :

I've worked in a similar problem and here goes my solution:

# coding: utf - 8
# python2 / django1 .6 .5

""
" 
That 's a first solution I got to use CommaSeparatedIntegerFields with SelectMultiple widget. 
My intension is to change this solution to a custom Widget that inherits from SelectMultiple. **
   * It still needs refactoring ** *
   ""
"

models.py

from django.db
import models

MY_CHOICES = (
   (1, 'escolha1'),
   (2, 'escolha2'),
   (3, 'escolha3'),
   (4, 'escolha4'),
   (5, 'escolha5'),
)

class MeuConteudo(models.Model):
   meu_campo = models.CommaSeparatedIntegerField(
      blank = True, max_length = 255,
   )

forms.py

from django
import forms
from minhaapp.models
import MeuConteudo, MY_CHOICES

class CommaSeparatedSelectInteger(forms.MultipleChoiceField):
   def to_python(self, value):
   if not value:
   return ''
elif not isinstance(value, (list, tuple)):
   raise ValidationError(
      self.error_messages['invalid_list'], code = 'invalid_list'
   )
return ','.join([str(val) for val in value])

def validate(self, value):
   ""
"
Validates that the input is a string of integers separeted by comma.
""
"
if self.required and not value:
   raise ValidationError(
      self.error_messages['required'], code = 'required'
   )

# Validate that each value in the value list is in self.choices.
for val in value.split(','):
   if not self.valid_value(val):
   raise ValidationError(
      self.error_messages['invalid_choice'],
      code = 'invalid_choice',
      params = {
         'value': val
      },
   )

def prepare_value(self, value):
   ""
" Convert the string of comma separated integers in list"
""
return value.split(',')

class MeuConteudoMultipleForm(forms.ModelForm):
   meu_campo = CommaSeparatedSelectInteger(
      choices = MY_CHOICES,
      widget = forms.SelectMultiple
   )

class Meta:
   model = MeuConteudo

Suggestion : 2

Django form with fields from two different models,Django multiple forms on one page with inherited models,How can i create django models , views , forms with different names,django filtering querysets causes 'AppRegistryNotReady: Models aren't loaded yet.' with forms within models.py

I've worked in a similar problem and here goes my solution:

# coding: utf - 8
# python2 / django1 .6 .5

""
" 
That 's a first solution I got to use CommaSeparatedIntegerFields with SelectMultiple widget. 
My intension is to change this solution to a custom Widget that inherits from SelectMultiple. **
   * It still needs refactoring ** *
   ""
"

models.py

from django.db
import models

MY_CHOICES = (
   (1, 'escolha1'),
   (2, 'escolha2'),
   (3, 'escolha3'),
   (4, 'escolha4'),
   (5, 'escolha5'),
)

class MeuConteudo(models.Model):
   meu_campo = models.CommaSeparatedIntegerField(
      blank = True, max_length = 255,
   )

forms.py

from django
import forms
from minhaapp.models
import MeuConteudo, MY_CHOICES

class CommaSeparatedSelectInteger(forms.MultipleChoiceField):
   def to_python(self, value):
   if not value:
   return ''
elif not isinstance(value, (list, tuple)):
   raise ValidationError(
      self.error_messages['invalid_list'], code = 'invalid_list'
   )
return ','.join([str(val) for val in value])

def validate(self, value):
   ""
"
Validates that the input is a string of integers separeted by comma.
""
"
if self.required and not value:
   raise ValidationError(
      self.error_messages['required'], code = 'required'
   )

# Validate that each value in the value list is in self.choices.
for val in value.split(','):
   if not self.valid_value(val):
   raise ValidationError(
      self.error_messages['invalid_choice'],
      code = 'invalid_choice',
      params = {
         'value': val
      },
   )

def prepare_value(self, value):
   ""
" Convert the string of comma separated integers in list"
""
return value.split(',')

class MeuConteudoMultipleForm(forms.ModelForm):
   meu_campo = CommaSeparatedSelectInteger(
      choices = MY_CHOICES,
      widget = forms.SelectMultiple
   )

class Meta:
   model = MeuConteudo

Suggestion : 3

我有一个django应用程序,希望在django的管理界面中显示多个选项复选框。我不想使用manytomanyfield为我的选择创建单独的模型。型号.py

我有一个django应用程序,希望在django的管理界面中显示多个选项复选框。我不想使用manytomanyfield为我的选择创建单独的模型。
型号.py

from django.db
import models

STAFF_BUSINESS_TYPES = {
   (1, "Foo"),
   (2, "Bar"),
   (3, "Cat"),
   (4, "Dog")
}

class Business(models.Model):
   name = models.CharField(max_length = 255, unique = True)
business_types = models.CommaSeparatedIntegerField(max_length = 32, choices = STAFF_BUSINESS_TYPES)

from business.models
import Business, STAFF_BUSINESS_TYPES
from django.forms
import CheckboxSelectMultiple, ModelForm, MultipleChoiceField

class BusinessForm(ModelForm):
   business_types = MultipleChoiceField(required = True, widget = CheckboxSelectMultiple, choices = STAFF_BUSINESS_TYPES)

class Meta:
   model = Business
fields = ['name', 'business_types']

def clean_business_types(self):
   data = self.cleaned_data['business_types']
cleaned_data = ",".join(data)
return cleaned_data

我也遇到过类似的问题,下面是我的解决方案:

# coding: utf - 8
# python2 / django1 .6 .5

""
" 
That 's a first solution I got to use CommaSeparatedIntegerFields with SelectMultiple widget. 
My intension is to change this solution to a custom Widget that inherits from SelectMultiple. **
   * It still needs refactoring ** *
   ""
"

Suggestion : 4

django.forms.ModelForm() , django.forms.CharField() , django.db.models.Model() , django.forms.Form()

def __init__(self, topic, * args, ** kwargs):
   super(CommentMoveForm, self).__init__( * args, ** kwargs)
self.fields['comments'] = forms.ModelMultipleChoiceField(
   queryset = Comment.objects.filter(topic = topic),
   widget = forms.CheckboxSelectMultiple
)
def make_entry_field(self, fieldsubmission = None):

   the_choices = [(k, v) for k, v in self.config.items() if k.startswith("choice_") and self.config[k]]
the_choices = sorted(the_choices, key = lambda choice: (int)(re.findall(r '\d+', choice[0])[0]))

initial = []

if fieldsubmission:
   initial = fieldsubmission.data['info']

c = self.CustomMultipleChoiceField(required = self.config['required'],
   label = self.config['label'],
   help_text = self.config['help_text'],
   choices = the_choices,
   widget = forms.CheckboxSelectMultiple(),
   initial = initial)

return c
def __init__(self, * args, ** kwargs):
   super().__init__( * args, ** kwargs)
self.fields['emri'].widget.attrs.update({
   'class': 'form-control'
})

# class LendetForm(forms.ModelForm):

   # class Meta:
   # model = ProvimetMundshme
# fields = '__all__'

# def __init__(self, * args, ** kwargs):
   # super().__init__( * args, ** kwargs)
# self.fields['program'].widget.attrs.update({
   'class': 'form-control',
   'data-type': 'program-listener'
})
# self.fields['semester'].widget.attrs.update({
   'class': 'form-control'
})
# self.fields['year'].widget.attrs.update({
   'class': 'form-control'
})
# self.fields['level'].widget.attrs.update({
   'class': 'form-control'
})

# course = forms.MultipleChoiceField(
   # widget = forms.CheckboxSelectMultiple,
   # choices = [(c.pk, c.name) for c in Course.objects.all()],
   #)
def __init__(self, project, * args, ** kwargs):
   kwargs.setdefault('label_suffix', '')
super(SiteBulkEditForm, self).__init__( * args, ** kwargs)

self.fields['sites'] = forms.ModelMultipleChoiceField(
   widget = forms.CheckboxSelectMultiple,
   queryset = project.sites.all(),
)

for attr in project.site_meta_attributes:
   q_type = attr['question_type']
q_name = attr['question_name']

if q_type == 'Number':
   field = forms.FloatField()
elif q_type == 'Date':
   field = forms.DateField()
elif q_type == 'MCQ':
   options = attr.get('mcq_options') or[]
choices = [o.get('option_text') for o in options]
choices = [(c, c) for c in choices]
field = forms.ChoiceField(choices = choices)
else:
   field = forms.CharField()

self.fields[q_name] = field
def __init__(self, * args, ** kwargs):
   super().__init__( * args, ** kwargs)
self.helper = FormHelper()
if settings.TARGET_PERMISSIONS_ONLY:
   self.common_layout = Layout('facility', 'target_id', 'observation_type')
else:
   self.fields['groups'] = forms.ModelMultipleChoiceField(Group.objects.none(),
      required = False,
      widget = forms.CheckboxSelectMultiple)
self.common_layout = Layout('facility', 'target_id', 'observation_type', 'groups')
self.helper.layout = Layout(
   self.common_layout,
   self.layout(),
   self.button_layout()
)
def __init__(self, * args, ** kwargs):
   super().__init__( * args, ** kwargs)
if not settings.TARGET_PERMISSIONS_ONLY:
   self.fields['groups'] = forms.ModelMultipleChoiceField(Group.objects.none(),
      required = False,
      widget = forms.CheckboxSelectMultiple)

Suggestion : 5

If the model field has choices set, then the form field’s widget will be set to Select, with choices coming from the model field’s choices. The choices will normally include the blank choice which is selected by default. If the field is required, this forces the user to make a selection. The blank choice will not be included if the model field has blank=False and an explicit default value (the default value will be initially selected instead).,When fields are missing from the form (for example because they have been excluded), these fields will not be set by the save() method. You can find more information about this restriction, which also holds for regular ModelForms, in Selecting the fields to use.,The form field’s label is set to the verbose_name of the model field, with the first character capitalized.,If either of these are used, the order the fields appear in the form will be the order the fields are defined in the model, with ManyToManyField instances appearing last.

>>> from django.forms
import ModelForm
   >>>
   from myapp.models
import Article

# Create the form class. >>>
class ArticleForm(ModelForm):
   ...class Meta:
   ...model = Article
   ...fields = ['pub_date', 'headline', 'content', 'reporter']

# Creating a form to add an article. >>>
   form = ArticleForm()

# Creating a form to change an existing article. >>>
   article = Article.objects.get(pk = 1) >>>
   form = ArticleForm(instance = article)
from django.db
import models
from django.forms
import ModelForm

TITLE_CHOICES = (
   ('MR', 'Mr.'),
   ('MRS', 'Mrs.'),
   ('MS', 'Ms.'),
)

class Author(models.Model):
   name = models.CharField(max_length = 100)
title = models.CharField(max_length = 3, choices = TITLE_CHOICES)
birth_date = models.DateField(blank = True, null = True)

def __str__(self): # __unicode__ on Python 2
return self.name

class Book(models.Model):
   name = models.CharField(max_length = 100)
authors = models.ManyToManyField(Author)

class AuthorForm(ModelForm):
   class Meta:
   model = Author
fields = ['name', 'title', 'birth_date']

class BookForm(ModelForm):
   class Meta:
   model = Book
fields = ['name', 'authors']
from django
import forms

class AuthorForm(forms.Form):
   name = forms.CharField(max_length = 100)
title = forms.CharField(
   max_length = 3,
   widget = forms.Select(choices = TITLE_CHOICES),
)
birth_date = forms.DateField(required = False)

class BookForm(forms.Form):
   name = forms.CharField(max_length = 100)
authors = forms.ModelMultipleChoiceField(queryset = Author.objects.all())
from django.forms
import ModelForm
from django.core.exceptions
import NON_FIELD_ERRORS

class ArticleForm(ModelForm):
   class Meta:
   error_messages = {
      NON_FIELD_ERRORS: {
         'unique_together': "%(model_name)s's %(field_labels)s are not unique.",
      }
   }
>>> from myapp.models
import Article
   >>>
   from myapp.forms
import ArticleForm

# Create a form instance from POST data. >>>
   f = ArticleForm(request.POST)

# Save a new Article object from the form 's data. >>>
   new_article = f.save()

# Create a form to edit an existing Article, but use
# POST data to populate the form. >>>
   a = Article.objects.get(pk = 1) >>>
   f = ArticleForm(request.POST, instance = a) >>>
   f.save()
# Create a form instance with POST data. >>>
   f = AuthorForm(request.POST)

# Create, but don 't save the new author instance. >>>
   new_author = f.save(commit = False)

# Modify the author in some way. >>>
   new_author.some_field = 'some_value'

# Save the new instance. >>>
   new_author.save()

# Now, save the many - to - many data
for the form. >>>
   f.save_m2m()