保存通过模型表单集创建的表单时发生错误

时间:2020-02-09 18:39:17

标签: django django-forms formset

我是Django学习者。 1.我需要在单个页面中为模型创建多个表单。 2.所以我使用modelformset_factory创建了表单集。 3.我有2个模型。a)模型寄存器b)模型GSPRequest。 4.ModelGSPRequest有一个名为registered_model的字段,它是ModelRegister的外键。 5.但是在我输入了modelformset的所有字段并单击提交以保存后。我在使用外键字段时遇到以下错误。

请帮助进一步进行操作。


Exception Type: ValueError
Exception Value:    
Cannot assign "'G6'": "ModelGSPRequest.registered_model" must be a "ModelRegister" instance.
Exception Location: C:\Python3.6.0\MyScripts\djangoprojects\gsptracker\venv\lib\site-packages\django\db\models\fields\related_descriptors.py in __set__, line 211

下面是我的代码:

models.py:

class ModelRegister(models.Model):
    """
        This class is used to register the model.
    """
    FLOAT_CHOICES = [[float(x), float(x)] for x in range(1, 21)]
    model_leader = models.CharField("Model leader", max_length=128)
    model_name = models.CharField(max_length=128, verbose_name="ModelName")
    model_no = models.CharField(max_length=128, verbose_name="ModelNo")
    os_name = models.ForeignKey(OSName, on_delete=models.CASCADE, verbose_name="OSName",default=" ")
    os_version = models.FloatField(choices=FLOAT_CHOICES)
    chipset_type = models.ForeignKey(ChipsetType,on_delete=models.CASCADE, verbose_name="chipsetType")
    chipset_name = models.ManyToManyField(Chipset)

    class Meta:
        verbose_name_plural = "ModelRegisteredList"

    def __str__(self):
        return self.model_name


class ModelGSPRequest(models.Model):
    """
        This class is used to raise Model GSP request.
    """

    FLOAT_CHOICES = [[float(x),float(x)] for x in range(1,21)]
    registered_model = models.ForeignKey(ModelRegister,on_delete=models.CASCADE, verbose_name="ModelName")
    model_nos_for_reg_model = models.ManyToManyField(ModelNumber,default="")
    #registered_model_no = models.CharField(max_length=128, verbose_name="ModelNo",default=" ")
    registered_os_name = models.ForeignKey(OSName, on_delete=models.CASCADE, verbose_name="OSName",default=" ")
    registered_os_version = models.FloatField(choices=FLOAT_CHOICES)
    registered_chipset_type = models.ForeignKey(ChipsetType, on_delete=models.CASCADE, verbose_name="chipsetType",default=" ")
    registered_chipset_name = models.ManyToManyField(Chipset)

    model_gsp_requester = models.CharField("Model GSP Requester", max_length=128,default=" ")
    integrator = models.CharField("Integrator", max_length=100,default=" ")
    region = models.ForeignKey(Region, on_delete=models.CASCADE, verbose_name="Region",default=" ")
    rel_cycle = models.ForeignKey(ReleaseCycle, on_delete=models.CASCADE, verbose_name="Release Cycle",default=" ")
    rel_start_date = models.DateField(default=" ")
    rel_end_date = models.DateField(default=" ")
    rel_type = models.ForeignKey(ReleaseType, on_delete=models.CASCADE, verbose_name="Release Type",default=" ")
    bingroup = models.ForeignKey(BinaryGroup, on_delete=models.CASCADE, verbose_name="BinaryGroup", default=" ")
    base_os_fingerprint = models.CharField(max_length=200, verbose_name="Base OS FingerPrint",blank=True,null=True)
    mpss_build_id = models.CharField(max_length=200,default=" ")
    tz_build_id = models.CharField(max_length=200,default=" ")
    previous_approved_sas_board = models.CharField(max_length=128,default=" ")
    previous_approved_manifest = models.CharField(max_length=128,default=" ")
    select_model_suffix = models.ForeignKey(ModelSuffix, on_delete=models.CASCADE,default=" ")
    cupss_group = models.CharField(max_length=128,verbose_name="CUPSS Group",default=" ")
    cupss_name = models.CharField(max_length=128,verbose_name="CUPSS Name",default=" ")
    previous_swv = models.CharField(max_length=128,default=" ")
    current_swv = models.CharField(max_length=128,default=" ")
    previous_swov = models.CharField(max_length=128,default=" ")
    current_swov = models.CharField(max_length=128,default=" ")
    previous_svn = models.CharField(max_length=128,default=" ")
    current_svn = models.CharField(max_length=128,default=" ")
    previous_rev = models.CharField(max_length=128,default=" ")
    current_rev = models.CharField(max_length=128, default=" ")
    fota_images_path = models.CharField(max_length=200,default=" ")
    #requested_Time = models.DateTimeField(auto_now_add=True,default=" ")

    class Meta:
        verbose_name_plural = "ModelGSPRequests"

    def __str__(self):
        return self.model_gsp_requester + self.integrator + str(self.pk)

forms.py:

class ModelRegisterForm(ModelForm):
    """
        This class is used to register the model information.
    """

    class Meta:
        model = ModelRegister
        exclude = ['model_leader']
        #fields = '__all__'


    @property
    def helper(self):
        helper = FormHelper()
        helper.form_tag = 'model_register_form'
        helper.layout = Layout(
            Fieldset(
               'Registered Model Details',
                #Row('model_leader' ),
                Row('model_name','model_no'),
                Row('os_name', 'os_version'),
                Row('chipset_type','chipset_name')
            )
        )

        return helper


class ModelRegisterForm(ModelForm):
    """
        This class is used to register the model information.
    """

    class Meta:
        model = ModelRegister
        exclude = ['model_leader']
        #fields = '__all__'


    @property
    def helper(self):
        helper = FormHelper()
        helper.form_tag = 'model_register_form'
        helper.layout = Layout(
            Fieldset(
               'Registered Model Details',
                #Row('model_leader' ),
                Row('model_name','model_no'),
                Row('os_name', 'os_version'),
                Row('chipset_type','chipset_name')
            )
        )

        return helper


def unique_values():
    return [("","---------------")]+list(ModelRegister.objects.values_list('model_name','model_name').order_by('model_name').distinct())


class ModelGSPRequestForm(ModelForm):
    """
        This class is used to define the form fields to raise the model GSP request.
    """
    registered_model = forms.ChoiceField(required=False,choices=unique_values)


    class Meta:
        model = ModelGSPRequest
        exclude = ['model_gsp_requester']

    #choices=[]
    def __init__(self, *args, **kwargs):
        super(ModelGSPRequestForm, self).__init__(*args, **kwargs)
        #self.form_tag = False
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Fieldset("Add Model GSP Request",
                     Row('registered_model','model_nos_for_reg_model','registered_os_name','registered_os_version','registered_chipset_type',
                         'registered_chipset_name','integrator','region','rel_cycle','rel_start_date','rel_end_date',
                         'rel_type','bingroup','base_os_fingerprint','mpss_build_id','tz_build_id',
                         'previous_approved_sas_board','previous_approved_manifest','select_model_suffix',
                         'cupss_group','cupss_name','previous_swv','current_swv','previous_swov','current_swov',
                         'previous_svn','current_svn','previous_rev','current_rev','fota_images_path')
                     )
            )
        self.fields['model_nos_for_reg_model'].queryset = ModelNumber.objects.none()

ModelGSPRequestFormSet = modelformset_factory(ModelGSPRequest, form=ModelGSPRequestForm, extra=1, can_delete=True)

views.py:

def create_model_gsp_request_form(request,id=None):
    print("Inside create_model_gsp_request_form")
    template_name = "ModelGSPRequest.html"
    heading_message = "ModelGSPRequest"

    if id:
        action = 'edit'
        model = get_object_or_404(ModelGSPRequest, pk=id)
    else:
        action = 'submit'
        model = ModelGSPRequest()

    message = ""

    if request.method == 'GET':
        print("Get request in create_model_gsp_request_form")
        # we don't want to display the already saved model instances
        #formset = ModelGSPRequestFormSet(queryset=ModelGSPRequest.objects.none(),instance=model)
        formset = ModelGSPRequestFormSet()
        registered_model_details = serializers.serialize("json", ModelRegister.objects.all())
        print("registered_model_details:", registered_model_details)
    elif request.method == 'POST':
        print("post request in create_model_gsp_request_form")
        formset = ModelGSPRequestFormSet(request.POST,request.FILES)
        if formset.is_valid():
            for form in formset:
                # only save if name is present
                #if form.cleaned_data.get('name'):

                    new_form = form.save(commit=False)
                    new_form.model_gsp_requester = request.user.username
                    new_form.save()
                    formset.save_m2m()
            return redirect('ModelGSPRequestList')
    return render(request, template_name, {
            'formset': formset,
            'heading': heading_message,
            'registered_model_data': registered_model_details,
            'action':action
        })

ModelGSPRequest.html:

<!DOCTYPE html>
{% extends "base.html" %}
{% load crispy_forms_tags %}

{% block static %}
{% endblock static %}

{% block content %}
<form action="" method="post">
    {% csrf_token %}
    <div class="container">
          {{ formset.management_form }}
            <table class="table">


                {% for form in formset.forms %}
                    {% if forloop.first %}
                        <thead>
                        <tr>
                            {% for field in form.visible_fields %}
                                <th>{{ field.label|capfirst }}</th>
                            {% endfor %}
                        </tr>
                        </thead>
                    {% endif %}
                    <tr class="{% cycle row1 row2 %} formset_row">
                        {% for field in form.visible_fields %}
                            <td>
                                {# Include the hidden fields in the form #}
                                {% if forloop.first %}
                                    {% for hidden in form.hidden_fields %}
                                        {{ hidden }}
                                    {% endfor %}
                                {% endif %}
                                {{ field.errors.as_ul }}
                                {{ field }}
                            </td>
                        {% endfor %}
                    </tr>
                {% endfor %}
            </table>

        <button type="submit" class="btn btn-primary">
            {% if action == "submit" %}
                   <span class="fas fa-plus"></span>Submit
            {% else %}
                   <span class="fas fa-edit"></span>Update
            {% endif %}
        </button>

    </div>
    </form>

{% endblock content %}

{% block scripts %}
    <script type="text/javascript">
        $('.formset_row').formset({
            addText: 'add model gsp request',
            deleteText: 'remove',
            prefix: 'modelgsp_set'
        });
    </script>
{% endblock scripts %}
[![ModelFormset created view][1]][1]

请在表单集中找到所选值foreign key的屏幕截图。

点击提交时抛出“无法分配“'G6'””:

"ModelGSPRequest.registered_model" must be a "ModelRegister" instance."

0 个答案:

没有答案