Data is not getting into database from Django form

I press ‘submit’ button, there is ‘post’ request in the terminal, but there is no new model in database.

forms.py

class PinCreationForm(forms.ModelForm):
    image = forms.ImageField(widget=forms.ClearableFileInput(attrs={
        'class':'create-pin-file-input'
    }))
    name = forms.CharField(widget=forms.TextInput(attrs={
        'class': 'create-pin-text-input', 'placeholder': 'Богатый мужчина'
    }))
    description = forms.CharField(widget=forms.TextInput(attrs={
        'class': 'create-pin-text-input', 'placeholder': 'Мужик стоит дрочит'
    }))
    tags = forms.CharField(widget=forms.TextInput(attrs={
        'class': 'create-pin-text-input', 'placeholder': 'Спорт, Машина, Огород'
    }))
    class Meta:
        model = PinModel
        fields = ('image', 'name', 'description', 'tags')

models.py

class PinModel(models.Model):
    name = models.CharField(max_length=50)
    description = models.TextField(null=True, blank=True)
    tags = models.TextField()
    image = models.ImageField(upload_to='pin_images')
    user = models.ForeignKey(to=User, on_delete=models.CASCADE)

views.py

class CreatePinView(CreateView):
    model = PinModel
    form_class = PinCreationForm
    template_name="pinapp/create-pin.html"
    success_url = reverse_lazy('users:login')

html

section class="create-pin-section">
    <div class="create-pin-div">
        <h2>Create Pin</h2>
        <form action="{% url 'create-pin' %}" class="create-pin-form" method="post">
            {% csrf_token %}
            <label for="{{ form.image.id_for_label }}">Choose Pic</label>
            {{ form.image }}
            <label for="{{ form.name.id_for_label }}">Choose da name</label>
            {{ form.name }}
            <label for="{{ form.description.id_for_label }}">Choose da description</label>
            {{ form.description }}
            <label for="{{ form.tags.id_for_label }}">Choose da tags</label>
            {{ form.tags }}
            <button type="submit">Create</button>
        </form>
    </div>
</section>

i want to explain, that i want is for the ‘user’ field to be filled in with the user who submitted the form

i tried everything that i found, no results.

First of all you have file inputs in your form, so you must use enctype="multipart/form-data":

<form ..., enctype="multipart/form-data">
    ...
</form>

Regarding your question you can override CreateView methods (such as post or form_valid), an example:

class CreatePinView(CreateView):
    ...
        
    def form_valid(self, form):
        """If the form is valid, save the associated model."""
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return super().form_valid(form)

Leave a Comment