If I leave everything as it is, then an error pops up when submitting the form
"Select a valid choice. That choice is not one of the available choices."
And, for example, if in forms.py I change Product.objects.values_list('product_name') to a class with one field, for example, Category.objects.all(), the form is submitted without errors
But I need exactly the first option, where I select a specific class field (product_name), so that there are the necessary options in the form in the select...
Who knows how to solve this problem?
models.py:
class Account(models.Model):
uploader_mail = models.EmailField(max_length=254)
body = models.CharField(max_length=4096)
product = models.ForeignKey('Product', on_delete=models.PROTECT)
class Product(models.Model):
product_name = models.CharField(max_length=400)
description = models.CharField(max_length=4096)
price = models.DecimalField(max_digits=8, decimal_places=2)
geo = models.CharField(max_length=2)
product_logo = models.ImageField(upload_to='img/logos', blank=True)
category = models.ForeignKey('Category', on_delete=models.PROTECT)
def __str__(self):
return self.product_name, self.description, self.geo,
class Category(models.Model):
category = models.CharField(max_length=100)
def __str__(self):
return self.category
forms.py:
class AddForm(forms.Form):
uploader_mail = forms.EmailField(
label='Owner mail',
initial='test@test.test',
widget=forms.EmailInput(attrs={'class': 'form-control'}))
body = forms.CharField(
label='Data line by line',
widget=forms.Textarea(attrs={'class': 'form-control','wrap': "off", }))
category = forms.ModelChoiceField(
queryset=Product.objects.values_list('product_name', flat=True),
label='Category',
empty_label=None,
widget=forms.Select(attrs={'class': 'form-select'}))
views.py:
def edit(request):
if request.method == 'POST':
form = AddForm(request.POST)
if form.is_valid():
print(form.cleaned_data)
else:
form = AddForm()
editable = {'form': form, }
return render(request, 'goods_list/edit.html', editable)