I am trying to save manytomany relationship. I have a form(in the template) that submits photos for the Business model. Business has manytomany relationship with BusinessPhotos.
As a result I am getting Business saved, and BusinessPhotos saved, but they are not linked.
When I look at Business model in the admin interface I see that BusinessPhotos associated with Businss are there, and I can select them.
What am i doing wrong?
I want for the photos to be added to the business.photos field automatically.
UPDATE AFTER TROUBLESHOOTING
I should’ve used request.FILES.get(“photo”) to get the files instead of request.POST.get(“photo”)
I was not saving Photos at all, BusinessPhoto objects I show in the screenshot were added by me through admin panel and i confused them for a successful addition…
class Business(models.Model):
...
photos = models.ManyToManyField("BusinessPhoto", null=True, blank=True)
...
class BusinessPhoto(models.Model):
photo = models.ImageField(
upload_to=business_upload_location,
null=True,
blank=True,
default="business/none/default.png",
)
timestamp = models.DateTimeField(default=timezone.now)
is_primary = models.BooleanField(default=False)
@login_required
def add_business(request):
if request.method == "POST":
...
photo = request.POST.get("photo")
photo_2 = request.POST.get("photo_2")
photo_3 = request.POST.get("photo_3")
business = Business(
user_id=user_id,
name=name,
description=description,
type=type,
website=website,
street=street,
city=city,
state=state,
country=country,
zip_code=zip_code,
schedule=schedule,
phone=phone,
email=email,
)
business.save()
if photo:
business_photo_primary = BusinessPhoto(
business_id=business, photo=photo, is_primary=True
)
business_photo_primary.save()
business.photos.add(business_photo_primary)
if photo_2:
business_photo_2 = BusinessPhoto(business_id=business, photo=photo_2)
business_photo_2.save()
business.photos.add(business_photo_2)
if photo_3:
business_photo_3 = BusinessPhoto(business_id=business, photo=photo_3)
business_photo_3.save()
business.photos.add(business_photo_3)
return redirect("index")
return render(request, "reviewerx/add_business.html", {})