I have been learning django for the last few months, and have been working on an ecommerce project to further my learning, but I’ve been absolutely stumped by an issue I’ve been having recently.
I’m using a ForeignKey to add multiple images to each product, and I currently have a form that allows me to create a post and add up to 20 images to it, I found some help online to make that form work and have studied it a lot to make sure I understand it, but when I tried to make it into an editing form I’ve gotten completely lost.
Here is my code
models.py
from django.db import models
from django.template.defaultfilters import slugify
from users.models import User
# Create your models here.
def get_thumbnail_filename(instance, filename):
title = instance.name
slug = slugify(title)
return "post_images/%s-%s" % (slug, filename)
class Product(models.Model):
seller = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=200)
description = models.TextField()
created = models.DateTimeField(auto_now_add=True)
price = models.FloatField()
thumbnail = models.ImageField(upload_to=get_thumbnail_filename, null=True)
def __str__(self):
return self.name
def get_image_filename(instance, filename):
title = instance.product.name
slug = slugify(title)
return "post_images/%s-%s" % (slug, filename)
class Images(models.Model):
product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE, null=True)
img = models.ImageField(upload_to=get_image_filename,
verbose_name='Image')
class Meta:
verbose_name_plural = "Images"
views.py
@login_required
def add_product(request):
ImageFormSet = modelformset_factory(Images,
form=ImageForm, extra=20)
#'extra' means the number of photos that you can upload ^
if request.method == 'POST':
postForm = ProductForm(request.POST, request.FILES)
formset = ImageFormSet(request.POST, request.FILES,
queryset=Images.objects.none())
if postForm.is_valid() and formset.is_valid():
post_form = postForm.save(commit=False)
post_form.user = request.user
post_form.save()
for form in formset.cleaned_data:
#this helps to not crash if the user
#do not upload all the photos
if form:
image = form['img']
photo = Images(product=post_form, img=image)
photo.save()
# use django messages framework
messages.success(request,
"Yeeew, check it out on the home page!")
return HttpResponseRedirect("/")
else:
print(postForm.errors, formset.errors)
else:
postForm = ProductForm()
formset = ImageFormSet(queryset=Images.objects.none())
return render(request, 'core/product-form.html',
{'postForm': postForm, 'formset': formset})
This is the part that where I can get a queryset to fill a form, but when I go to save the form reloads blank with no images saying the fields are required
@login_required
def edit_product(request, pk):
pro_in = get_object_or_404(Product, id=pk)
ImageFormSet = modelformset_factory(Images, fields='__all__', extra=20, max_num=20)
#'extra' means the number of photos that you can upload ^
if request.method == 'GET':
context = {'postForm': ProductForm(instance=pro_in), 'formset':ImageFormSet(queryset=Images.objects.filter(product_id=pk))}
return render(request, 'core/product-form.html', context)
if request.method == 'POST':
postForm = ProductForm(request.POST, request.FILES, instance=pro_in)
formset = ImageFormSet(request.POST, request.FILES, queryset=Images.objects.filter(product_id=pk))
if postForm.is_valid() and formset.is_valid():
post_form.save()
fromset.save()
# use django messages framework
messages.success(request,
"Yeeew, check it out on the home page!")
return HttpResponseRedirect("/")
else:
print(postForm.errors, formset.errors)
else:
postForm = ProductForm()
formset = ImageFormSet(queryset=Images.objects.none())
return render(request, 'core/product-form.html',
{'postForm': postForm, 'formset': formset})
If you need to see my forms.py, and or urls.py just ask.
Any help is greatly appreciated!
DuggyWantsYourSoul24 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.