NOT NULL constraint failed: django

2

I'm getting an error when I try to create a new element by a form, trying that the user who is already with the session started can upload an image and it is recognized as his in the relationship with the base of data that I have in models.py .

NOT NULL constraint failed: pins_pin.user_id

models.py

class Pin(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=140)
    image = models.ImageField(upload_to='static/img/pins')

    def __str__(self):
        return self.title

forms.py

from .models import Pin

class PinCreateForm(ModelForm):
    class Meta:
        model = Pin
        fields = ('title', 'image')

views.py

class PinCreate(CreateView):
    model = Pin
    form_class = PinCreateForm
    template_name = 'pins/pin_create.html'

    def form_valid(self, form):
        user = self.request.user
        form.save()
        return redirect('/')

Thanks in advance to anyone who can help me

    
asked by ikenshu 29.08.2017 в 06:18
source

1 answer

2

should be:

def form_valid(self, form):
    form.instance.user = self.request.user
    return redirect('/')
    
answered by 29.08.2017 / 20:40
source