class Product(models.Model):
symbol = models.CharField(_('Symbol'), max_length=250)
name = models.CharField(_('Name'), max_length=250)
is_visible = models.BooleanField(default=False)
class ProductForm(forms.ModelForm):
product = forms.ModelChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Product.objects.all())
if request.method == 'POST':
form = ProductForm(data=request.POST)
if form.is_valid():
ids = form.cleaned_data.get('product') # Example: ['pk', 'pk']
for id in ids:
product = Product.objects.get(pk=id)
product.is_visible = True
product.save()
ProductFormSet = modelformset_factory(Product, fields=('is_visible',))
я так понимаю выведутся просто чексбоксы? Хотелось бы как то поставить названия продукта возле чексбокса, чтобы пользователь знал что изменяет. Что можете подсказать по этому поводу? Внизу привел код из views.py и не могу понять нужно ли указывать instance в форме и как форма узнает какую именно запись редактирует.def manage_products(request):
data = dict()
ProductFormSet = modelformset_factory(Product, fields=('is_visable',))
if request.method == 'POST':
product_formset = ProductFormSet(request.POST)
if product_formset.is_valid():
product_formset.save()
data['form_is_valid'] = True
data['html_product'] = render_to_string('project/product_list.html', {'product_formset': product_formset})
else:
data['form_is_valid'] = False
else:
product_formset= ProductFormSet()
data['html_manage_products_form'] = render_to_string('project/manage_products.html', {'product_formset': product_formset}, request=request)
return JsonResponse(data)
ProductFormSet = modelformset_factory(Product, fields=('is_visible',))
product_formset = ProductFormSet(request.POST, queryset=Product.objects.all())
{% for product_form in product_formset %}
{% for field in product_form %}
<input type="checkbox" name="" value="(field.is_visable.value)">(field.name.value)</input>
{% endfor %}
{% endfor %}
{% for product_form in product_formset %}
{{ product_form.is_visible.field }}<label for="{{ product_form.is_visible.id_for_label }}">{{ product_form.name.value }}</label>
{% endfor %}
ProductFormSet = modelformset_factory(Product, fields=('name', 'is_visible',), widgets={'name': forms.HiddenInput()})
{% for product_form in product_formset %}
{{ product_form.name }}
{{ product_form.is_visible }}<label for="{{ product_form.is_visible.id_for_label }}">{{ product_form.name.value }}</label><br>
{% endfor %}
def manage_products(request):
data = dict()
if request.method == 'POST':
product_formset = ProductFormSet(data=request.POST, queryset=Product.objects.all())
if product_formset.is_valid():
product_formset.save()
data['form_is_valid'] = True
data['html_product'] = render_to_string('project/product_list.html', {'product_formset': product_formset})
else:
data['form_is_valid'] = False
else:
product_formset= ProductFormSet()
data['html_manage_products_form'] = render_to_string('project/manage_products.html', {'product_formset': product_formset}, request=request)
return JsonResponse(data)
Traceback (most recent call last):
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
response = get_response(request)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 296, in do_revision_context
return func(*args, **kwargs)
File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 631, in manage_products
if product_formset.is_valid():
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\formsets.py", line 321, in is_valid
self.errors
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\formsets.py", line 295, in errors
self.full_clean()
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\formsets.py", line 342, in full_clean
for i in range(0, self.total_form_count()):
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\formsets.py", line 116, in total_form_count
return min(self.management_form.cleaned_data[TOTAL_FORM_COUNT], self.absolute_max)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\formsets.py", line 98, in management_form
code='missing_management_form',
django.core.exceptions.ValidationError: ['Данные управляющей формы отсутствуют или были повреждены']
def formset_test(request):
formset = ProductFormSet(request.POST or None, queryset=Product.objects.all())
if request.method == 'POST':
print formset.is_valid()
if formset.is_valid():
formset.save()
context = {
'formset': ProductFormSet(queryset=Product.objects.all())
}
return render(request, 'template.html', context)
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = 'is_visible',
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs)
self.label_suffix = ''
self.fields['is_visible'].label = self.instance.name
ProductFormSet = modelformset_factory(Product, max_num=0, form=ProductForm)
{% for product_form in product_formset %}
<label for="{{ product_form.is_visible.id_for_label }}">{{ product.is_visible.label }}</label>
{{ product_form.is_visible }}
<br>
{% endfor %}
<form method='post'>
{% csrf_token %}
{% for form in formset %}
<label for="{{ form.is_visible.id_for_label }}">
{{ form.is_visible }} {{ form.is_visible.label }}
</label>
{% endfor %}
<input type='submit'>
</form>
<div class="modal-body">
<input id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" value="5" type="hidden">
<input id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" value="5" type="hidden">
<input id="id_form-MIN_NUM_FORMS" name="form-MIN_NUM_FORMS" value="0" type="hidden">
<input id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" value="0" type="hidden">
<label for="id_form-0-is_visible">ПРОДУКТ 1.</label>
<input checked="checked" id="id_form-0-is_visible" name="form-0-is_visible" type="checkbox">
<input id="id_form-0-code" name="form-0-code" value="2043c5e4-6d8d-4c70-9971-dd1b2a7f47c7" type="hidden">
<label for="id_form-1-is_visible">ПРОДУКТ 2.</label>
<input id="id_form-1-is_visible" name="form-1-is_visible" type="checkbox">
<input id="id_form-1-code" name="form-1-code" value="21d916ed-21b3-432f-bfb2-a38b19481b44" type="hidden">
<label for="id_form-2-is_visible">ПРОДУКТ 3.</label>
<input id="id_form-2-is_visible" name="form-2-is_visible" type="checkbox">
<input id="id_form-2-code" name="form-2-code" value="398c3757-6997-4d19-8fae-18c6c45f9b83" type="hidden">
<label for="id_form-3-is_visible">ПРОДУКТ 4.</label>
<input id="id_form-3-is_visible" name="form-3-is_visible" type="checkbox">
<input id="id_form-3-code" name="form-3-code" value="b984e6ba-3386-4235-ad2c-898528540977" type="hidden">
<label for="id_form-4-is_visible">ПРОДУКТ 5.</label>
<input id="id_form-4-is_visible" name="form-4-is_visible" type="checkbox">
<input id="id_form-4-code" name="form-4-code" value="e2605779-8b21-443d-8cf0-5aec42669c63" type="hidden">
</div>
<div class="modal-body">
<label for="id_form-0-is_visible">ПРОДУКТ 1.</label>
<input checked="checked" id="id_form-0-is_visible" name="form-0-is_visible" type="checkbox">
<label for="id_form-1-is_visible">ПРОДУКТ.</label>
<input id="id_form-1-is_visible" name="form-1-is_visible" type="checkbox">
<label for="id_form-2-is_visible">ПРОДУКТ 3.</label>
<input id="id_form-2-is_visible" name="form-2-is_visible" type="checkbox">
<label for="id_form-3-is_visible">ПРОДУКТ 4.</label>
<input id="id_form-3-is_visible" name="form-3-is_visible" type="checkbox">
<br>
<label for="id_form-4-is_visible">ПРОДУКТ 5.</label>
<input id="id_form-4-is_visible" name="form-4-is_visible" type="checkbox">
</div>
<form method='post'>
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
<label for="{{ form.is_visible.id_for_label }}">
{{ form.is_visible }} {{ form.is_visible.label }}
</label>
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endfor %}
<input type='submit'>
</form>