Hi folks wonder if anyone could help me with this. I have a very simple for which includes a ImageField to handle uploads. I’m getting the error below.
ValueError: Field 'id' expected a number but got......b'\xff\xd8\xff\xe1\x0.........
I’m pretty sure it’s because the image field is a M2M, but I ‘think’ i’m handling that correctly in my views. Any help much appreciated.
Models … I need a House
to have many images…relevant code
class Image(models.Model):
image = models.ImageField()
def __str__(self):
return self.image.name
class House(models.Model):
image = models.ManyToManyField(Image, null=True, blank=True)
def __str__(self):
return self.name
Form…
class HouseForm(ModelForm):
class Meta:
model = House
fields = ["name", "description", "status", "image", "link", "date" ]
image = forms.ImageField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['name'].required = False
Views…(Httpresponse for testing)
def houseform(request):
if request.method == 'POST':
form = HouseForm(request.POST, request.FILES)
print(request.POST, "file", request.FILES)
if form.is_valid():
house = form.save(commit=False)
house.save()
form.save_m2m()
return HttpResponse("foo")
else:
print(form.errors)
return HttpResponse("bar")
else:
form = HouseForm()
return render(request,
template_name="core/partials/forms/house-form.html",
context={'form': form })
Template (using widget tweaks)…form inlcudes enctype…
<form method="post"
action="{% url 'houseform' %}"
enctype="multipart/form-data">
<div class="flex flex-col gap-3">
{% csrf_token %}
<label class="text-sm" for="name">Name</label>
{% render_field form.name placeholder="Name" class="input input-bordered w-full max-w-xs"%}
<label class="text-sm" for="image">Image</label>
{% render_field form.image placeholder="Image" class="file-input file-input-bordered file-input-accent w-full max-w-xs"%}
<button type="submit">Submit</button>
<a hx-boost="true" href="{% url 'dashboard' %}" class="text-blue-500 hover:text-blue-700">Back</a>
</form>