Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django UpdateView:无法获取表单字段以显示数据库值_Python_Django_Django Views - Fatal编程技术网

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

Python Django UpdateView:无法获取表单字段以显示数据库值,python,django,django-views,Python,Django,Django Views,我找到了相同问题的多个答案,但不幸的是,我似乎无法找到答案:( 该表单具有我的模型“PhysicalPart”中“subcategory”字段的下拉列表,“subcategory”字段的值在表单创建时动态更新(使用“category”参数) 不幸的是,我无法通过下拉列表显示所有子类别,也无法同时选择数据库中的子类别。我似乎也无法从数据库中检索“short_description”值 在我了解UpdateView类并决定改用它之前,它曾经是有效的 任何关于如何解决我的问题的见解都将不胜感激 for

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

该表单具有我的模型“PhysicalPart”中“subcategory”字段的下拉列表,“subcategory”字段的值在表单创建时动态更新(使用“category”参数)

不幸的是,我无法通过下拉列表显示所有子类别,也无法同时选择数据库中的子类别。我似乎也无法从数据库中检索“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


{%csrf_令牌%}

类型
{{form.subcategory}

简短说明
{{form.short_description}}

拯救 取消
据我所知,您正在尝试编辑一个实例。这是您在Django中的操作方式,它应该使用正确的值自动填充您的输入:

my_record = MyModel.objects.get(id=XXX)
form = MyModelForm(instance=my_record)
有关此答案的更多详细信息:


如果您的模型正确完成(使用关系),您就不需要为Select提供选项。

我的问题是,我没有在UpdateView类中区分“GET”调用和“POST”调用,我正在尝试完成POST()中的所有操作方法。我花了一段时间才弄明白,但现在我想它清楚了。 我最初使用get()方法,但我意识到get_context_data()更适合,因为它可以自动加载大部分上下文(例如实例和表单),而不必在get()方法中从头开始做任何事情

在清理UpdateView类的代码时,似乎还需要将ModelFormMixin添加到PartUpdate类的声明中,以便get_context_data()方法自动加载与目标模型/实例关联的表单(否则它看起来不会这样做)

以下是我更新的views.py代码:

class PartUpdate(UpdateView, ModelFormMixin):
    model = PhysicalPart
    template_name = 'part_update.html'
    form_class = PartForm
    success_url = reverse_lazy('part-list')

    def get_context_data(self, **kwargs):
        # Load context from GET request
        context = super(PartUpdate, self).get_context_data(**kwargs)
        # Get id from PhysicalPart instance 
        context['part_id'] = self.object.id
        # Get category from PhysicalPart instance
        context['part_category'] = self.object.category
        # Add choices to form 'subcategory' field
        context['form'].fields['subcategory'].choices = SubcategoryFilter[self.object.category]

        # Return context to be used in form view
        return context

    def post(self, request, *args, **kwargs):
        # Get instance of PhysicalPart
        self.object = self.get_object()
        # Load form
        form = self.get_form()
        # Add choices to form 'subcategory' field
        form.fields['subcategory'].choices = SubcategoryFilter[self.object.category]
        # Check if form is valid and save PhysicalPart instance
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

你能展示你的模型吗?@BleuBizarre我不认为这个问题与我的模型有任何关系,它只是一堆CharField(“子类别”)。以便能够理解您的模型。为什么您的子类别不是ForeignKey?在您强制选择筛选器时,您确定这是否有效?可能尝试使用一些随机值进行双重检查,如果这不是您看不到任何内容的原因ForeignKey>允许您具有一对一关系基本上它将存储wa的ID但是当你在django中请求它时,它将直接是与UpdateView类外部的IDOI相关的对象,你说的很好。我在这里也尝试过,但是如果我将“form=super(PartUpdate,self)。get_form(self.form_class)”替换为“form=PartForm(request.POST,instance=self.object)”我得到了同样的结果。。。
class PartUpdate(UpdateView, ModelFormMixin):
    model = PhysicalPart
    template_name = 'part_update.html'
    form_class = PartForm
    success_url = reverse_lazy('part-list')

    def get_context_data(self, **kwargs):
        # Load context from GET request
        context = super(PartUpdate, self).get_context_data(**kwargs)
        # Get id from PhysicalPart instance 
        context['part_id'] = self.object.id
        # Get category from PhysicalPart instance
        context['part_category'] = self.object.category
        # Add choices to form 'subcategory' field
        context['form'].fields['subcategory'].choices = SubcategoryFilter[self.object.category]

        # Return context to be used in form view
        return context

    def post(self, request, *args, **kwargs):
        # Get instance of PhysicalPart
        self.object = self.get_object()
        # Load form
        form = self.get_form()
        # Add choices to form 'subcategory' field
        form.fields['subcategory'].choices = SubcategoryFilter[self.object.category]
        # Check if form is valid and save PhysicalPart instance
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)