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

2024-06-02 08:25:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

该表单具有我的模型“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

<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>

Tags: selfdivformobjectcontextbuttonformsdescription
2条回答

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

my_record = MyModel.objects.get(id=XXX)
form = MyModelForm(instance=my_record)

有关此答案的更多详细信息:how to edit model data using django forms

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

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

通过清理UpdateView类here的代码,似乎还需要将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)

相关问题 更多 >