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
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')
Related
I am having trouble making if/else work in my django app, I want to check if a listing is booked, booked is a boolean field and the listing is a foreign key to the Booking class where the user selects a listing to book. Now I just want to know how that foreign key can be checked if the listing is booked so it fails to book and gives an error.
views.py
#login_required
def profile(request):
if request.method == "GET":
tickets = models.Booking.objects.all().filter(user=request.user)
return render(request, "profile.html", {'form': forms.BookingForm(), 'tickets': tickets})
else:
try:
form = forms.BookingForm(request.POST)
new_ticket = form.save(commit=False)
new_ticket.user = request.user
new_ticket.save()
messages.success(request, 'Booking Created Successfully')
return redirect('profile')
except ValueError:
return render(request, 'profile.html', {'form': forms.BookingForm()})
models.py
class Listing(models.Model):
title = models.CharField(max_length=50)
content = models.TextField(max_length=755)
price = MoneyField(max_digits=5, decimal_places=2)
booked = models.BooleanField(default=False)
seller = models.ForeignKey(User, on_delete=models.CASCADE)
# avail_days = models.ForeignKey(Days, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Booking(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
listing = models.ForeignKey(Listing, on_delete=models.CASCADE) # how to check if listing is booked and deny if it is True ?
# day = models.OneToOneField(Days, on_delete=models.CASCADE)
date_booked = models.DateField(auto_now_add=True)
def __str__(self):
return self.user.username
If you want to use booked field in Listing model, you can do this (you can also render Listing objects with booked=False):
views.py
#login_required
def profile(request):
if request.method == "GET":
tickets = models.Booking.objects.all().filter(user=request.user)
return render(request, "profile.html", {'form': forms.BookingForm(), 'tickets': tickets})
else:
try:
form = forms.BookingForm(request.POST)
new_ticket = form.save(commit=False)
# here you can do something like
if new_ticket.listing.booked:
messages.error(request, 'Booked Already')
return redirect('profile')
new_ticket.user = request.user
new_ticket.save()
messages.success(request, 'Booking Created Successfully')
return redirect('profile')
except ValueError:
return render(request, 'profile.html', {'form': forms.BookingForm()})
models.py
class Listing(models.Model):
title = models.CharField(max_length=50)
content = models.TextField(max_length=755)
price = MoneyField(max_digits=5, decimal_places=2)
booked = models.BooleanField(default=False)
seller = models.ForeignKey(User, on_delete=models.CASCADE)
# avail_days = models.ForeignKey(Days, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Booking(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
listing = models.ForeignKey(Listing, on_delete=models.CASCADE) # how to check if listing is booked and deny if it is True ?
# day = models.OneToOneField(Days, on_delete=models.CASCADE)
date_booked = models.DateField(auto_now_add=True)
def __str__(self):
return self.user.username
def save(self, *args, **kwargs):
self.listing.booked = True
self.listing.save()
super().save(*args, **kwargs)
here user i want user and userprofile. useing exclude. when i add userprofile error 'WSGIRequest' object has no attribute 'userprofile'
modelform
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ('categories', 'title', 'description', 'image', 'price')
exclude = ('user','userprofile')
view
#login_required
def productpost(request):
form = ProductForm()
if request.method == "POST":
form = ProductForm(request.POST, request.FILES)
if form.is_valid():
form = form.save(commit=False)
form.user = request.user
form.userprofile = request.userprofile
form.save()
return success(request)
else:
print("The Form Is Invalid")
return render(request, 'product/postproduct.html', {'form': form})
Model
class Product(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
userprofileinfo = models.ForeignKey(UserProfileInfo, on_delete=models.CASCADE)
categories = models.ForeignKey(Categories, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
description = models.TextField()
image = models.FileField()
price = models.IntegerField()
pub_date = models.DateTimeField('date published', auto_now_add=True)
def __str__(self):
return self.title
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
These are the files included in this Directory
views.py
#login_required(login_url='/account/login/')
def TaskCreateView(request,pk,todo_id):
if not request.user.is_authenticated:
return redirect('accounts:index')
else:
instance = get_object_or_404(Level, pk=pk)
qs = instance.todo_set.get(id = todo_id)
#user = Task.objects.filter(student=request.user)
todo = Task.objects.filter(todo=qs, student=request.user)
if todo.exists():
messages.warning(request, 'You Already Completed This Task')
return HttpResponseRedirect(instance.get_absolute_url())
form = StudentTaskForm(request.POST or None,request.FILES or None)
if form.is_valid():
obj = form.save(commit=False)
obj.student = request.user
obj.todo = qs
obj.level = instance
obj.save()
return redirect('student:dashboard')
return render(request,'task_form.html',{'form':form,"qs":qs})
models.py
class Task(models.Model):
level = models.ForeignKey(Level, on_delete=models.CASCADE)
todo = models.ForeignKey(ToDo, on_delete=models.CASCADE)
student = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=150)
content = models.TextField()
image = models.ImageField()
timestamp = models.TimeField(auto_now=True)
datestamp = models.DateField(auto_now_add=True, auto_now=False)
like = models.ManyToManyField(User,related_name='user_likes')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('student:task-detail', kwargs={'pk': self.pk})
objects = PostManager()
#property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
#property
def get_content_type(self):
instance = self
content_type = ContentType.objects.get_for_model(instance.__class__)
return content_type
forms.py
class StudentTaskForm(forms.ModelForm):
title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control',' type': "text",'placeholder':'Enter Title'}))
content = forms.CharField(widget=SummernoteWidget())
image = forms.ImageField()
class Meta:
model = Task
fields = [
'title',
'content',
'image',
]
widgets = {
'content': SummernoteWidget(),
}
I am trying to save the fields into the Task model after form save .I am encountering the error after I submit the form. I am unable to increment the foreign key value in the table of primary ones.Following is the error
null value in column "user_id" violates not-null constraint\nDETAIL: Failing row contains (34,30,null) )
Your code doesn't include a user foreign key so you shouldn't get an error about user_id being null.
Perhaps you renamed user to student, and then forgot to make migrations and migrate.
I just want to filter select field in a form, regarding a currently logged user. Every user has own categories and budgets - I want to display only a models related with a currently logged user. I've tried stuff with filtering before is_valid field, but with no result. Please, find my code below:
views.py
#login_required
def day_data_multiadd(request, no_of_lines=0):
no_of_lines = int(no_of_lines)
CostFormSet = modelformset_factory(Cost, form=DataAddForm, extra=no_of_lines)
if request.method == 'POST' and 'form' in request.POST:
formset = CostFormSet(request.POST, request.FILES)
if formset.is_valid():
for form in formset.forms:
f = form.save(commit=False)
f.user = request.user
f.save()
else:
formset = CostFormSet(queryset=Cost.objects.none())
if request.method == 'POST' and 'no_line' in request.POST:
generate_form = MultiaddGenerateForm(request.POST)
if generate_form.is_valid():
cd = generate_form.cleaned_data
return HttpResponseRedirect(reverse('core_sm:day_data_multiadd', args=(cd['formy'], )))
else:
generate_form = MultiaddGenerateForm()
return render(request, 'core_sm/costs/multi_add.html', {'formset': formset,
'no_of_lines': no_of_lines,
'generate_form': generate_form})
forms.py
class DataAddForm(forms.ModelForm):
class Meta:
model = Cost
fields = ['title', 'value', 'publish', 'category', 'budget']
exclude = ['user']
labels = {
'title': _('Tytuł'),
'value': _('Wartość'),
'publish': _('Data'),
'category': _('Kategoria'),
'budget': _('Budżet')
}
models.py
class Category(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
title = models.CharField(max_length=200)
publish = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now=True)
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_ur(self):
return reverse('core_sm:category_detail', args=[self.id])
class Budget(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
title = models.CharField(max_length=200, db_index=True)
value = models.DecimalField(decimal_places=2, max_digits=10)
publish = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now=True)
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('core_sm:budget_detail', args=[self.id])
class Cost(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
budget = models.ForeignKey(Budget, related_name='cost')
category = models.ForeignKey(Category, related_name='cost')
title = models.CharField(max_length=200, db_index=True)
publish = models.DateField(default=timezone.now)
created = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now=True)
value = models.DecimalField(max_digits=10, decimal_places=2)
class Meta:
ordering = ('-publish',)
def get_absolute_url(self):
return reverse('core_sm:stats_detail', args=[self.publish.year,
self.publish.strftime('%y'),
self.publish.strftime('%m'),
self.publish.strftime('%d')])
def __str__(self):
return self.title
According to the docs you can pass custom parameters to formsets forms.
class DataAddForm(forms.ModelForm):
class Meta:
model = Cost
fields = ['title', 'value', 'publish', 'category', 'budget']
exclude = ['user']
labels = {
'title': _('Tytuł'),
'value': _('Wartość'),
'publish': _('Data'),
'category': _('Kategoria'),
'budget': _('Budżet')
}
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
self.fields['category'].queryset = Category.objects.filter(user=user)
self.fields['budget'].queryset = Budget.objects.filter(user=user)
super(DataAddForm, self).__init__(*args, **kwargs)
views.py
formset = CostFormSet(queryset=Cost.objects.none(), form_kwargs={'user': request.user})
I have models.py with a date field like this
class Topic(models.Model):
text = models.CharField(max_length=200)
date_added = models.DateTimeField('date published')
def __str__(self):
return self.text
View.py like this:
def new_topic(request):
if request.method != 'POST':
form = TopicForm()
else:
form = TopicForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('blog:topics'))
context = {'form' : form}
return render(request, 'blog/new_topic.html', context)
form.py :
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['text', 'date_added']
labels = {'text': ''}
Now problem is that i need to automatic add date to the field . To have any DB inputs.
Use auto_now_add in the field definition:
date_added = models.DateTimeField('date published', auto_now_add=True)