i want to save an object to db and it worked one time but now it doesnt, i suspect that is something to do with the Glossary
Everything
views.py
#login_required
def product_form_view(request):
if request.method == 'POST':
form = Product_Form(request.POST, request.FILES)
if form.is_valid():
product_form = form.save()
product_form.save()
return redirect('product_management_view')
else:
form = Product_Form()
return render(request, 'product-form.html', {'form': form})
models.py
class Product (models.Model):
sub_chapter = models.ForeignKey(Sub_Chapter, on_delete=models.CASCADE)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
glossary = models.ManyToManyField(Glossary, blank=True )
name = models.CharField(max_length=40, blank=False, null=False)
description = models.TextField(null=True)
product_image = models.ImageField(
upload_to='media/images/product_images', blank=False, null=False)
reference = models.CharField(max_length=40, blank=False, null=False)
width = models.PositiveIntegerField()
height = models.PositiveIntegerField()
length = models.PositiveIntegerField()
unit_price = models.DecimalField(
max_digits=15, decimal_places=4, null=True)
polution = models.DecimalField(decimal_places=8, max_digits=15, null=True, blank=True )
technical_implementation = models.TextField(null=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse_lazy("manufacter_product_view", kwargs={'id': self.pk})
forms.py
class Product_Form(forms.ModelForm):
sub_chapter = forms.ModelChoiceField(queryset=Sub_Chapter.objects.all(),
required=True, widget=forms.Select())
supplier = forms.ModelChoiceField(queryset=Supplier.objects.all(),
required=True, widget=forms.Select())
glossary = forms.ModelChoiceField(queryset=Glossary.objects.all(),
required=False, widget=forms.SelectMultiple())
product_image = forms.ImageField(
required=True, widget=forms.FileInput())
class Meta():
model = Product
fields =[ 'name', 'description', 'reference', 'width', 'height', 'length', 'polution', 'unit_price', 'technical_implementation', 'sub_chapter', 'supplier', 'glossary', 'product_image', ]
There is a bug in your product_form_view, you are calling the save method on product_form variable i.e product_form.save() but product_form will have None in it as form.save() will return None on successfully saving the object,so it will break the code there.And you don't need to again call the save method at all.Calling form.save() is enough for saving the object and you should move the code in else part out of it as it not currently handling the form invalid case.
Your code should be like this:
#login_required
def product_form_view(request):
if request.method == 'POST':
form = Product_Form(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('product_management_view')
form = Product_Form()
return render(request, 'product-form.html', {'form': form})
Related
I get 2 different errors the first one is
Django Model IntegrityError: NOT NULL constraint failed:
I checked the solution for this, people said I've to make my FK attributes null = true and blank = true
so this solved that.
The second error I got after that was in my views.py
'CommentForm' object has no attribute 'cleaned_data'
My Views.py file:
def project(request, pk):
form = CommentForm()
project = ProjectModel.objects.get(id=pk)
contextt ={
"project": project,
"form":form,
}
if request.method == "POST":
form.save()
return redirect(request, "/dashboard")
else:
return render(request, "projects.html", contextt)
and my Models.py:
class ProjectModel(models.Model):
caption = models.CharField(max_length=100)
video = models.FileField(upload_to="video/%y", validators=[file_size])
ProjectName = models.CharField(max_length=50, )
ProjectDescription = models.TextField(max_length=1000,)
Project_Background_picture = models.ImageField(
upload_to=settings.MEDIA_ROOT, default='/static/img/default.png')
Approved = models.BooleanField(default=False)
Finished = models.BooleanField(default=False)
Goal = models.DecimalField(
decimal_places=3, max_digits=6, blank=True, null=True)
Pledges = models.DecimalField(
decimal_places=3, max_digits=6, blank=True, null=True)
Number_of_investors = models.IntegerField(blank=True, null=True)
FirstReward = models.TextField(max_length=1000, default=' 10$ ')
SecondReward = models.TextField(max_length=1000, default=' 25$')
ThirdReward = models.TextField(max_length=1000, default='50$')
FourthReward = models.TextField(max_length=1000, default='100$ +s')
def __str__(self):
return self.caption
class comment(models.Model):
ProjectModel = models.ForeignKey(
ProjectModel, related_name='comments', on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=255)
CommentBody = models.TextField(default='comment here!', max_length=1000 )
date_added = models.DateTimeField(auto_now_add=True)
def _str_(self):
return '%s - %s' % (self.ProjectModel.caption, self.name)
try this:
def project(request, pk):
form = CommentForm()
project = ProjectModel.objects.get(id=pk)
contextt ={
"project": project,
"form ":form ,
}
if request.method == 'POST' :
form = CommentForm(data=request.POST)
if form.is_valid():
form= form.save(commit=False) #new line
form.ProjectModel = project #new line
form.save()
return redirect("/dashboard")
else:
return render(request, "projects.html", contextt)
When I enter info into my formset, the images gets erased and I'm not able to advance to the next page. No errors appear on the page. Essentially, the form data isn't passing "is_valid". I'm pretty certain that there is something wrong in my view.py.
Models.py
class Testimonial(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
image = VersatileImageField('image_testimonial', upload_to=upload_location, validators=[file_size], null=True, blank=True)
message = models.CharField(max_length=300, default='', null=True, blank=True)
name = models.CharField(max_length=100, default='', null=True, blank=True)
city = models.CharField(max_length=100, default='', null=True, blank=True)
state = models.CharField(max_length=100, default='', null=True, blank=True)
def __str__(self):
return self.author.username
forms.py
class TestimonialForm (forms.ModelForm):
class Meta:
model = Testimonial
fields = ('image', 'message', 'name', 'city', 'state',)
views.py
#login_required(login_url="/accounts/login/")
def testimonials(request):
TestimonialFormSet = modelformset_factory(Testimonial, form=TestimonialForm, extra=3)
if request.method == 'POST':
formset = TestimonialFormSet(request.POST or None, request.FILES or None)
if formset.is_valid():
instances = formset.save(commit=False)
for instance in instances: #for instance in instances.cleaned_data:
instance.author = request.user
fix_orientation(instance.image)
instance.save()
return redirect('/accounts/profile/')
else:
args = {'formset': formset}
return render(request, 'accounts/page6.html', args)
else:
formset = TestimonialFormSet(queryset=Testimonial.objects.filter(author=request.user))
return render(request, 'accounts/page6.html', {'formset': formset})
I had to
a) include {{formset.errors}} in my template to render the error that was preventing submission
b) include {{ form.id }} in the template even though id isn't part of my model. This seems to be an odd quirk of formset, but alas, I can now submit the form.
Shoutout to Daniel Roseman for helping me find the answer!
this me again. I have some trouble with my code. I made a form from ModelForm which have a model with 8 attributes, but i want to user fill only one of them,and one from the system. The one that user fill is okay, but the one filled with system is not working.
models.py
class SeminarProposal(md.Model):
# diisi oleh mahasiswa
fileProposal = models.FileField()
# This is the one is filled with system
proposal = models.OneToOneField(Proposal,
on_delete=models.CASCADE,
related_name="propSid",
unique=True, blank=True, null=True)
masabimbingan = models.BooleanField(default=True)
# disi oleh admin
tanggal = models.DateField(default=timezone.now, blank=True,null=True)
tempat = models.CharField(max_length=30, blank=True, null=True)
# diisi oleh dosen pembimbing
dospemsetuju = models.BooleanField(default=False, blank=True)
# diisi oleh kaprodi
penguji1 = models.ForeignKey(Dosen,
on_delete=models.CASCADE,
related_name="penguji1",
blank=True, null=True)
penguji2 = models.ForeignKey(Dosen,
on_delete=models.CASCADE,
related_name="penguji2",
blank=True, null=True)
def __str__(self):
return "Sidang untuk " + self.proposal.judul
view.py
def daftarSeminar(request):
if request.method == 'POST':
form = FormSeminar(request.POST, request.FILES)
print(request.user)
if form.is_valid():
form.save(commit=False)
form.cleaned_data['proposal']
print(request.user)
prop = Proposal.objects.get(akun=request.user)
form.proposal = prop
print(form.proposal) #to confirm that this is not None
form.save()
return redirect('proposal:bimbingan')
else:
return render(request, 'sidprop.html' , {'oke': 'oke'})
return redirect('proposal:index')
form.py
class FormSeminar(forms.ModelForm):
class Meta:
model = SeminarProposal
fields = ['fileProposal','proposal']
Thanks in advance. Terimakasih.
Instead of changing the form data, get the object from form and change the object's data:
if form.is_valid():
obj = form.save(commit=False)
prop = Proposal.objects.get(akun=request.user)
obj.proposal = prop
obj.save()
return redirect('proposal:bimbingan')
I have a model Partner that is related to Product by a one to many relationships. I am using inlineformsets for the Product and I am gettig the following error which I don't understand:"KeyError at /partners/create/ 'name'"
my views are as follows:
def partner_create(request):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
ProductFormSet = inlineformset_factory(Partner, Product, form=ProductForm, extra=3, min_num=1)
if request.method == 'POST':
partnerForm = PartnerForm(request.POST or None, request.FILES or None)
formset = ProductFormSet(request.POST, request.FILES, queryset=Product.objects.none())
if partnerForm.is_valid() and formset.is_valid():
instance = partnerForm.save(commit=False)
instance.save()
for form in formset.cleaned_data:
name = form["name"]
description = form["description"]
price = form["price"]
image = form["image"]
product = Product(partner=instance, name=name, description=description, price=price, product_image=image)
product.save()
messages.success(request, "Partner Successfully Created")
else:
print partnerForm.errors, formset.errors
else:
partnerForm = PartnerForm()
formset = ProductFormSet(queryset=Product.objects.none())
return render(request, "partner_form.html", {"partnerForm": partnerForm, "formset": formset})
my forms.py are as follows:
class PartnerForm(forms.ModelForm):
mission = forms.CharField(widget=PagedownWidget(show_preview=False))
vision = forms.CharField(widget=PagedownWidget(show_preview=False))
# publish = forms.DateField(widget=forms.SelectDateWidget)
class Meta:
model = Partner
fields = [
"name",
"logo",
"banner_image",
"mission",
"vision",
"website_link",
"fb_link",
"twitter_link",
"ig_link",
]
class ProductForm(forms.ModelForm):
image = forms.ImageField(label='Image')
class Meta:
model = Product
fields = [
"partner",
"name",
"description",
"price",
"image",
]
My models.py are as follows:
def upload_location(instance, filename):
#filebase, extension = filename.split(".")
# return "%s/%s" %(instance.name, instance.id)
PartnerModel = instance.__class__
exists = PartnerModel.objects.exists()
if exists:
new_id = PartnerModel.objects.order_by("id").last().id + 1
else:
new_id = 1
file_name, file_extension = filename.split('.')
return "%s/%s/%s-%s.%s" %('partner',instance.name, file_name, new_id, file_extension)
class Partner(models.Model):
name = models.CharField(max_length=120)
logo = models.ImageField(upload_to=upload_location,
null=True,
blank=True,
width_field="width_field",
height_field="height_field")
banner_image = models.ImageField(upload_to=upload_location,
null=True,
blank=True,
width_field="width_field",
height_field="height_field")
mission = models.TextField()
vision = models.TextField()
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
# text = models.TextField()
website_link = models.CharField(max_length=120)
fb_link = models.CharField(max_length=120)
twitter_link = models.CharField(max_length=120)
ig_link = models.CharField(max_length=120)
slug = models.SlugField(unique=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
def __unicode__(self):
return self.name
def get_absolute_url(self):
return reverse("partners:detail", kwargs={"slug": self.slug})
# return "/partner/%s/" %(self.id)
def get_markdown(self):
mission = self.mission
markdown_text = markdown(mission)
return mark_safe(markdown_text)
#Creating a many to one relationship so that one can upload many Products
class Product(models.Model):
partner = models.ForeignKey(Partner, default=None)
name = models.CharField(max_length=120)
product_image = models.ImageField(upload_to=upload_location,
# product_image = models.ImageField(upload_to= (upload_location + '/' + name), Something like this need to append actual product name so these dont just get dumped in the media for partners
null=True,
blank=True,
width_field="width_field",
height_field="height_field",
verbose_name='Image',)
description = models.TextField()
price = models.DecimalField(max_digits=6, decimal_places=2, null=True)
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
def __unicode__(self): # __unicode__ on Python 2
return self.name
I would really like to understand what is going on as well as how to fix it or a hint in the right direction. Thank you in advance for your help!
To find out why you're getting the error, you should add some printing or logging to your code. What is the value of formset.cleaned_data? Is it what you think it should be?
There's a simpler approach that looping through the formset's cleaned_data. The docs show how to save a formset. You can save with commit=False, then set the partner field before saving to the database.
products = formset.save(commit=False)
for product in products:
product.partner=instance
product.save()
Note that if you do this, you should probably switch to a modelformset_factory instead of inlineformset_factory, and remove partner from the list of the fields of the ProductForm.
The formset form save method seems incorrect, use something like
for form in formset.cleaned_data:
if form.is_valid():
name = form.cleaned_data.get("name")
description = form.cleaned_data.get("description")
price = form.cleaned_data.get("price")
image = form.cleaned_data.get("image")
Please lemme know if this works :)
This is my model:
class User(models.Model):
name = models.CharField(max_length=50)
mail = models.CharField(max_length=50)
nickname = models.CharField(max_length=50)
def __str__ (self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=200)
lead = models.CharField(max_length=10, default='default')
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
user = models.ForeignKey(User, related_name="User", null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
This is my view:
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.published_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'post_new.html', {'form': form})
This is my forms.py:
class PostForm(forms.ModelForm):
selectuser = forms.ModelChoiceField(queryset=User.objects.all())
class Meta:
model = Post
fields = ('title','lead', 'text',)
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('name','nickname','mail')
My problem is that selected value from ModelChoiceField is saving to base without value just empty field. Can u help me resolve that problem?
My problem is that selected value from ModelChoiceField is saving to
base without value just empty field. Can u help me resolve that
problem?
The model field is Post.user, but your form field PostForm.selectuser. Try using user in the PostForm.
class PostForm(forms.ModelForm):
user = forms.ModelChoiceField(queryset=User.objects.all())
...