简体   繁体   中英

Django CreateView doesn't save object and doesn't give error

I'm working on a new project and I'm having difficulties adding new objects from the users page. It can be added from admin dashboard. This is the model:

class Product(models.Model):
    title = models.CharField(max_length=150)
    price = models.IntegerField()
    image = models.ImageField(upload_to='products')
    description = models.TextField(max_length=500)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title
        
    def get_absolute_url(self):
        return reverse('product-details', kwargs={'pk': self.pk})

I have this view:

class ProductCreateView(LoginRequiredMixin, CreateView):
    model = Product
    fields = ['title', 'image', 'description', 'price']

    def form_valid(self, form):
        form.instance.owner = self.request.user
        #form.save() # tried this too and it didn't work
        return super().form_valid(form)

product_form.html:

{% extends "index/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
    <div class="content-section">
        <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">Product</legend>
                {{ form|crispy }}
            </fieldset>
            <div class="form-group">
                <button class="btn btn-outline-info" type="submit">Save</button>
            </div>
        </form>
    </div>
{% endblock content%}

I tried a couple of times and I didn't work. So I searched for solutions and tried the following:

instance = form.save(commit=False)
instance.owner = self.request.user
instance.save()
return super().form_valid(instance)

and this

self.object.owner = self.request.user
self.object = form.save()
return super(ProductCreateView, self).form_valid(form)

within the form_valid(). Neither of them worked. So I can open the form and fill the fields. When I send it, the object is not saved but it doesn't give any error. It just reloads the form.

You are commenting #form.save() .

You have to uncomment it to make it save.

Ok, so after nearly one week of trying to fix the issue and not much help, I found a solution! form_valid() works fine the way it is, but the problem is in the form. Adding enctype fixes the problem:

<form method="POST" enctype="multipart/form-data">

The explanation I found for this is that without enctype the image data is not being passed correctly to the database. So it looks like the form is fine, but on the background it is not saving the image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM