简体   繁体   中英

Why the contents of the form changes?

I am tring to create dynamic list to choices of symbol field. I create that list inside view then put it to form constructor.

I want to take all data from Dictionary modal put it inside choices and show in my form but in the same time I dont need to show data which is already exist in Requirement modal.

At start it shows form correct: 在此处输入图片说明

Then when I try to click submit button form changes to this: (Whats wrong happenes?) 在此处输入图片说明

models.py:

class Dictionary(models.Model):
    symbol = models.CharField(_('Symbol'), max_length=250)
    name = models.CharField(_('Name'), max_length=250)

class Requirement(models.Model):
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    symbol = models.CharField(_('Symbol'), max_length=250)
    name = models.CharField(_('Name'), max_length=250)

forms.py:

class RequirementForm(forms.ModelForm):
    symbol = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)

    class Meta:
        model = Requirement
        fields = ('symbol',)

    def __init__(self, final_list, *args, **kwargs):
        super(RequirementForm, self).__init__(*args, **kwargs)
        self.fields['symbol'].choices = [(x[0], x[1]) for x in final_list)]

views.py:

def requirement_add(request, project_code):
    data = dict()
    project = get_object_or_404(Project, pk=project_code)

    requirements = Requirement.objects.filter(project=project_code)
    result = []
    for x in requirements:
         v = (x.symbol, x.name)
         result.append(v)
    full_result = [(x.symbol, x.name) for x in Dictionary.objects.all()]
    final_list= list(set(full_result) ^ set(result))

    if request.method == 'POST':
        form = RequirementForm(request.POST, final_list)
        if form.is_valid():
            requirement_dict = dict(((x.symbol, x.name) for x in Dictionary.objects.all()))
            symbols = form.cleaned_data.get('symbol')
            requirement = form.save(commit=False)
            for symbol in symbols:
                requirement.project = project
                requirement.symbol = symbol
                requirement.name = requirement_dict [symbol]
                requirement.pk = None
                requirement.save()
            data['form_is_valid'] = True
            requirements = Requirement.objects.filter(project=project_code)
            context = {'project': project, 'requirement': requirement, 'requirements': requirements}
            data['html_requirement'] = render_to_string('project/requirement_list.html', context)
        else:
            data['form_is_valid'] = False
    else:
        form = RequirementForm(final_list)
    context = {'project': project, 'form': form}
    data['html_requirement_form'] = render_to_string('project/requirement_add.html', context, request=request)
    return JsonResponse(data)

ERROR:

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 616, in requirement_add
    if form.is_valid():
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\forms.py", line 169, in is_valid
    return self.is_bound and not self.errors
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\forms.py", line 161, in errors
    self.full_clean()
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\forms.py", line 370, in full_clean
    self._clean_fields()
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\forms.py", line 382, in _clean_fields
    value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\widgets.py", line 626, in value_from_datadict
    return data.get(name)
AttributeError: 'list' object has no attribute 'get'

Finally I found my mistake! It was in this line:

RequirementForm(data=request.POST, final_list=final_list) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM