Answer the question
In order to leave comments, you need to log in
Why is only one entry created?
Hello! Faced a strange problem. Please help me fix it.
I display the REQUIREMENTS_CHOICES list with checkboxes, since I used MultipleChoiceField in the form. Next, I try to create several objects in the view, based on the data that was marked by the user. The problem is that only one record is created and only the data from the last checkbox marked by the user is used. What is my jamb? That is, if the user has marked, say, 3 checkboxes, it is necessary to create 3 objects using the data from the marked checkboxes.
models.py:
class Requirement(models.Model):
code = models.UUIDField(_('Code'), primary_key=True, default=uuid.uuid4, editable=False)
symbol = models.CharField(_('Symbol'), max_length=250)
name = models.CharField(_('Name'), max_length=250)
class AddForm(forms.ModelForm):
symbol= forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=REQUIREMENTS_CHOICES,)
class Meta:
model = Requirement
fields = ('symbol',)
REQUIREMENTS_CHOICES = (
('A', 'Name A'),
('B', 'Name B'),
('C', 'Name C'),
)
def requirement_add(request):
data = dict()
if request.method == 'POST':
form = AddForm(request.POST)
if form.is_valid():
list = dict(REQUIREMENTS_CHOICES) # {'C': 'Name C', 'A': 'Name A', 'B': 'Name B'}
symbols = form.cleaned_data.get('symbol') # ['A', 'B', 'C']
requirement = form.save(commit=False)
for symbol in symbols:
requirement.symbol = symbol
requirement.name = list[symbol]
requirement.save()
data['form_is_valid'] = True
requirements = Requirement.objects.filter()
context = {requirement': requirement, 'requirements': requirements}
data['html_requirement'] = render_to_string('project/requirement_list.html', context)
else:
data['form_is_valid'] = False
else:
form = AddForm()
context = {'form': form}
data['html_requirement_form'] = render_to_string('project/requirement_add.html', context, request=request)
return JsonResponse(data)
Answer the question
In order to leave comments, you need to log in
Finally found a solution. It was necessary to add to the view requirement.pk = None .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question