1

I'm trying to poplulate the fields in my "CreateDealerForm" for when I choose to edit. So far I can only populate the featured_image field and if I add featured_image to the widgets dictionary I get: '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)
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50
GTA.sprx
  • 817
  • 1
  • 8
  • 24
  • Remove "featured_image" from widgets. If it's already a file or image field then you don't need to set it's widget manually – Iain Shelvington Dec 22 '19 at 21:44
  • @IainShelvington the reason I was trying that is because I want to preview the image and I followed the answer to this post https://stackoverflow.com/questions/28764571/display-image-from-imagefield-by-means-of-form – GTA.sprx Dec 22 '19 at 21:47
  • `forms.ImageField` is not a widget, it is a form field – Iain Shelvington Dec 22 '19 at 21:49

1 Answers1

2

You are not handling the case when the request method is GET (when you first render the form for a user to edit the values). You need to handle this case and not pass data to the form or you will perform validation when you do not need to.

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)
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50