вот модель
class Tables(models.Model):
title = models.CharField(max_length=200)
start_price = models.IntegerField()
is_active = models.BooleanField(default=True)
summary = models.TextField(max_length=1000, help_text="Enter a brief description of your product")
def __str__(self):
return str(self.title)
class TableImage(models.Model):
table = models.ForeignKey(Tables, blank=True, null=True, default=None, on_delete=models.SET_NULL)
photo = models.ImageField()
is_main = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
def __str__(self):
return str(self.table)
вот форма
class TablesForm(forms.ModelForm):
class Meta:
model = Tables
fields = ['title', 'start_price', 'is_active', 'summary']
class TableImageForm(forms.ModelForm):
class Meta:
model = TableImage
fields = ['table','photo']
TableImageFormSet = inlineformset_factory(Tables,TableImage, fields=['photo', 'is_main', 'is_active'], exclude=[], extra=1)
вот views
class TableImageCreate(CreateView):
model = Tables
form_class=TablesForm
success_url=reverse_lazy('table_create')
template_name='auction/tables_form.html'
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
if self.request.POST:
data["photo"] = TableImageFormSet(self.request.POST, self.request.FILES)
else:
data["photo"] = TableImageFormSet()
return data
def form_valid(self, form):
context = self.get_context_data()
photo = context["photo"]
self.object = form.save()
if photo.is_valid():
photo.instance = self.object
photo.save()
return super().form_valid(form)
html вот
<form method="post" >
{% csrf_token %}
<table>
{{ form.as_p }}
</table>
<table>
{{ photo }}
</table>
<input type="submit" value="Save" /> <a href="{% url 'table_create' %}">back to the list</a>
</form>
после сохранения не добавляются записи картинок в бд