'ImageField'对象没有属性'value_from_datadict'

时间:2019-12-22 21:41:02

标签: django django-forms django-views

当我选择编辑时,我试图填充“ CreateDealerForm”中的字段。到目前为止,我只能填充featured_image字段,如果将featured_image添加到窗口小部件字典中,则会得到:'ImageField' object has no attribute 'value_from_datadict'

forms.py

class CreateDealerForm(forms.ModelForm):
    class Meta:
        model = Dealer
        fields = ('name', 'phone','website', 'address', 'featured_image',)
        widgets = {
            'name': forms.TextInput(attrs={'class': 'dealer-name-field', 'placeholder': 'Dealer name'}),
            'phone': forms.TextInput(attrs={'class': 'dealer-phone-field', 'placeholder': 'Dealer phone'}),
            'website': forms.TextInput(attrs={'class': 'dealer-website-field', 'placeholder': 'Dealer website'}),
            'address': forms.TextInput(attrs={'class': 'dealer-address-field', 'placeholder': 'Dealer address'}),
            "featured_image": forms.ImageField(),
        }

views.py

def update_dealer_view(request, slug):
    instance = get_object_or_404(Dealer, slug=slug)
    form = CreateDealerForm(request.POST, request.FILES, instance=instance)
    if form.is_valid():
        dealer = form.save(commit=False)
        dealer.save()
        return redirect('main:homepage_view')

    context = {
        "title": "Update - Dealer",
        "form": form,
        "instance": instance,
    }
    return render(request=request, template_name="main/create/create_dealer.html", context=context)

1 个答案:

答案 0 :(得分:0)

当请求方法为GET(首次为用户呈现表单以编辑值)时,您将无法处理这种情况。您需要处理这种情况,并且不要将数据传递给表单,否则将在不需要时执行验证。

def update_dealer_view(request, slug):
    instance = get_object_or_404(Dealer, slug=slug)
    if request.method == 'POST':
        form = CreateDealerForm(request.POST, request.FILES, instance=instance)
        if form.is_valid():
            dealer = form.save()
            return redirect('main:homepage_view')
    else:
        form = CreateDealerForm(instance=instance)
    context = {
        "title": "Update - Dealer",
        "form": form,
        "instance": instance,
    }
    return render(request=request, template_name="main/create/create_dealer.html", context=context)