Django UpdateView:无法获取表单字段以显示数据库值

我找到了相同问题的多个答案,但不幸的是,我似乎无法弄清楚:(


该表单在我的模型“PhysicalPart”中有一个“子类别”字段的下拉列表,“子类别”字段的值在表单创建时动态更新(使用“类别”参数)。


不幸的是,我无法让下拉菜单显示所有子类别并同时选择数据库中的一个。我似乎也无法从数据库中检索到“short_description”值。


在我了解 UpdateView 类并决定改用它之前,它曾经可以工作......


任何有关如何解决我的问题的见解将不胜感激!


forms.py


class PartForm(forms.ModelForm):

subcategory = forms.ChoiceField(choices=[])


class Meta:

    model = PhysicalPart

    fields = ['subcategory', 'short_description']

views.py


class PartUpdate(UpdateView):

model = PhysicalPart

template_name = 'part_update.html'

form_class = PartForm


def post(self, request, *args, **kwargs):

    # Load model instance

    self.object = self.get_object()

    # Load form

    form = super(PartUpdate, self).get_form(self.form_class)

    # Populating subcategory choices

    form.fields['subcategory'].choices = SubcategoryFilter[self.object.category]


    # Check if form valid and save data

    if form.is_valid():

        form.save()


        return redirect('part-list')


    # Update context before rendering

    context = self.get_context_data(**kwargs)

    context['part_id'] = self.object.pk

    context['part_category'] = self.object.category

    context['manufacturing_list'] = self.object.manufacturing.all()


    return render(request, self.template_name, context)

html


<form action="{% url 'part-update' pk=part_id category=part_category %}" method="post" style="display: inline">

    {% csrf_token %}

    <div class="form">

        <p class="font-weight-bold">Type</br>

        {{ form.subcategory }}

        </p>

    </div>

    <div class="form">

        <p class="font-weight-bold">Short Description</br>

        {{ form.short_description }}

        </p>

    </div>

    <button type="submit" class="btn btn-primary">Save</button>

</form>

<form action="{% url 'part-list' %}" style="display: inline">

    <button type="submit" class="btn btn-danger">Cancel</button>

</form>


临摹微笑
浏览 105回答 2
2回答

侃侃尔雅

我的问题是我没有区分UpdateView类中的“GET”和“POST”调用,我试图在post()方法中做所有事情。我花了一段时间才弄清楚,但现在我认为这很清楚。我最初使用get()方法,但我意识到get_context_data()更适合,因为它会自动加载大部分上下文(例如实例和表单),而不必在get()方法中从头开始做所有事情.在这里浏览 UpdateView 类的代码,似乎还需要将 ModelFormMixin 添加到PartUpdate类的声明中,以便get_context_data()方法自动加载与目标模型/实例关联的表单(否则它看起来不会不要这样做)。这是我更新的views.py代码:class PartUpdate(UpdateView, ModelFormMixin):&nbsp; &nbsp; model = PhysicalPart&nbsp; &nbsp; template_name = 'part_update.html'&nbsp; &nbsp; form_class = PartForm&nbsp; &nbsp; success_url = reverse_lazy('part-list')&nbsp; &nbsp; def get_context_data(self, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; # Load context from GET request&nbsp; &nbsp; &nbsp; &nbsp; context = super(PartUpdate, self).get_context_data(**kwargs)&nbsp; &nbsp; &nbsp; &nbsp; # Get id from PhysicalPart instance&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; context['part_id'] = self.object.id&nbsp; &nbsp; &nbsp; &nbsp; # Get category from PhysicalPart instance&nbsp; &nbsp; &nbsp; &nbsp; context['part_category'] = self.object.category&nbsp; &nbsp; &nbsp; &nbsp; # Add choices to form 'subcategory' field&nbsp; &nbsp; &nbsp; &nbsp; context['form'].fields['subcategory'].choices = SubcategoryFilter[self.object.category]&nbsp; &nbsp; &nbsp; &nbsp; # Return context to be used in form view&nbsp; &nbsp; &nbsp; &nbsp; return context&nbsp; &nbsp; def post(self, request, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; # Get instance of PhysicalPart&nbsp; &nbsp; &nbsp; &nbsp; self.object = self.get_object()&nbsp; &nbsp; &nbsp; &nbsp; # Load form&nbsp; &nbsp; &nbsp; &nbsp; form = self.get_form()&nbsp; &nbsp; &nbsp; &nbsp; # Add choices to form 'subcategory' field&nbsp; &nbsp; &nbsp; &nbsp; form.fields['subcategory'].choices = SubcategoryFilter[self.object.category]&nbsp; &nbsp; &nbsp; &nbsp; # Check if form is valid and save PhysicalPart instance&nbsp; &nbsp; &nbsp; &nbsp; if form.is_valid():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return self.form_valid(form)&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return self.form_invalid(form)

忽然笑

据我了解,您正在尝试编辑实例。这就是您在 Django 中的操作方式,它应该使用正确的值自动填充您的输入:my_record&nbsp;=&nbsp;MyModel.objects.get(id=XXX) form&nbsp;=&nbsp;MyModelForm(instance=my_record)有关此答案的更多详细信息:如何使用 django 表单编辑模型数据如果您的模型正确完成(使用关系),则不需要为 Select 提供选项。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python