P
P
Peterson_s2020-11-08 21:26:11
Django
Peterson_s, 2020-11-08 21:26:11

Why are images not saved in the database?

here is the model

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)

here is the form
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)

here are the 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 here
<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>

image records are not added to the database after saving

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Peterson_s, 2020-11-08
@Peterson_s

Here is the answer!!!)

<form method="post" enctype="multipart/form-data">
...
</form>

he asked - he decided)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question