Search code examples
pythondjangoformsdatetimeform-fields

Django DateTimeField and User Input fields not added


I am beginner to python Django. I'm working on practice project. I got stuck while adding a product. Its adds all the fields except two fields i. DateTimeField ii. User (who add the product)

The error which i'm facing is:

django.db.utils.IntegrityError: null value in column "pub_date" violates not-null constraint
DETAIL:  Failing row contains (3, Piano, Ball Pens(set of 3), 15, 30, 10, images/ballpens_QdhwoOa.jpg, null, null).

models.py

class Product(models.Model):
    companyName    = models.CharField(max_length=255)
    pro_name       = models.CharField(max_length=255)
    Purchase_Price = models.IntegerField()
    Sale_Price     = models.IntegerField()
    Quantity       = models.IntegerField()
    Picture        = models.ImageField(upload_to='images/')
    saler          = models.ForeignKey(User, on_delete=models.CASCADE)
    pub_date       = models.DateTimeField()

    def pub_date_pretty(self):
        return self.pub_date.strftime('%b %e %Y')

    def __str__(self):
        return self.pro_name

views.py

class AddProduct(TemplateView):
    template_name = 'stock/addproduct.html'

    def get(self, request):
        form = AddProductForm()
        args = {'form':form}
        return render(request, self.template_name, args)

    def post(self, request):
        form = AddProductForm(request.POST, request.FILES)
        if form.is_valid():
            productadded = form.save()
            productadded.saler =  request.user
            productadded.pub_date = timezone.datetime.now()
            productadded.save()
            return redirect('stock')
        else:
            args = {'form': form}
            return render(request, self.template_name, args)

In views.py, I am saving a user and date and time as you see in above forms.py


class AddProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ('companyName', 'pro_name', 'Purchase_Price', 'Sale_Price', 'Quantity', 'Picture' )

    def __init__(self, *args, **kwargs):
        super(AddProductForm, self).__init__(*args, **kwargs)
        self.fields['companyName'].label    = 'Company Name'
        self.fields['pro_name'].label       = 'Product Name'
        self.fields['Purchase_Price'].label = 'Purchase Price'
        self.fields['Sale_Price'].label     = 'Sale Price'

Your help will be appreciated. Thank You


Solution

  • do a small correction

           if form.is_valid():
                productadded = form.save(commit=False)
                productadded.saler =  request.user
                productadded.pub_date = timezone.datetime.now()
                productadded.save()
                return redirect('stock')