Adding a comment section form to my Django app - django

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)

Related

Django Forms - how to add the + sign for a Many2Many field

enter image description hereRelated to Django Forms and Many2Many
I have tried to look for ways to add the + to my django form when I want to add a new post to my webpage.
What I'm looking for is a similar function as the one in admin module. See picture.
I have tried to read though the docs but not sure what to look for. Have anybody build something similar?
my model looks like this
class Wine_taste(models.Model):
title = models.CharField(max_length=128, null=True, blank=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
category = models.ManyToManyField('Wine_Category', verbose_name='Kind of Wine',related_name='wcategory')
subcategory = models.ForeignKey('Wine_SubCategory', verbose_name='Wine type',on_delete=models.SET_NULL, null=True, blank=True)
review = models.TextField()
producer_taste = models.ForeignKey('Wine_Producer', verbose_name='Producer or shipper', on_delete=models.SET_NULL, null=True, blank=True )
grape_taste = models.ManyToManyField('Wine_Grapes', verbose_name='Grapes')
country_taste = models.ForeignKey('Wine_Country', verbose_name='Country of origin', on_delete=models.SET_NULL, null=True, blank=True )
sweetness = models.PositiveSmallIntegerField(choices=LEVELRATE_CHOICES, verbose_name='Rate Sweetness')
acid = models.PositiveSmallIntegerField(choices=LEVELRATE_CHOICES, verbose_name='Rate acid level')
fruit = models.PositiveSmallIntegerField(choices=LEVELRATE_CHOICES, verbose_name='Rate fruitness')
taste = models.PositiveSmallIntegerField(choices=RATE_CHOICES, verbose_name='Rate taste')
overall = models.PositiveSmallIntegerField(choices=RATE_CHOICES, verbose_name='Overall rate')
thumbnail = models.ImageField()
timestamp = models.DateTimeField(auto_now_add=True)
featured = models.BooleanField()
previous_post = models.ForeignKey('self', related_name='previous', on_delete=models.SET_NULL, null=True, blank=True)
next_post = models.ForeignKey('self', related_name='next', on_delete=models.SET_NULL, null=True, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('wine:wine-dyn', kwargs={"id": self.id})
def get_update_url(self):
return reverse('wine:wine-update', kwargs={"id": self.id})
def get_delete_url(self):
return reverse('wine:wine-delete', kwargs={"id": self.id})
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img = Image.open(self.thumbnail.path)
if img.height > 400:
new_height = 400
new_width = new_height / img.height * img.width
output_size = ((new_height, new_width))
img.thumbnail(output_size)
img.save(self.thumbnail.path)
#property
def get_comments(self):
return self.comments.all().order_by('-timestamp')
#property
def comment_count(self):
return Comment.objects.filter(post=self).count()
#property
def view_count(self):
return PostView.objects.filter(post=self).count()
Blockquote
this is my view:
def wine_detailed_create(request):
title = 'Create'
form = CreateForm(request.POST or None, request.FILES or None)
author = get_author(request.user)
if request.method == 'POST':
if form.is_valid():
form.instance.author = author
form.save()
return redirect (reverse('wine:wine-dyn', kwargs={'id': form.instance.id}))
context = {
'title': title,
'form': form
}
return render(request, 'wine/wine_create.html', context)
and my forms:
class CreateForm(forms.ModelForm):
class Meta:
model = Wine_taste
fields = ('title',
'country_taste',
'category',
'subcategory',
'producer_taste',
'grape_taste',
'review',
'thumbnail',
'sweetness',
'acid',
'fruit',
'taste',
'overall',
'featured',
'previous_post',
'next_post',)
Blockquote
br
Lars

form not saving into user model Django

I'm currently processing a payment thing for an online subscription service and in order to get the users info to send this stuff, I have a payment form.
But, for some reason the payment form is not saving to the users account. Everything else actually processes and the only error I can trigger is a 'NOT NULL constraint failed: memberships_usermembership.user_id'
Here's what I have in my view -
#login_required()
def payments(request):
user_membership = get_user_membership(request)
selected_membership = get_selected_membership(request)
form = SubscriptionForm()
if request.method == "POST":
form_data = {
'full_name': request.POST['full_name'],
'email': request.POST['email'],
'phone_number': request.POST['phone_number'],
'country': request.POST['country'],
'postcode': request.POST['postcode'],
'town_or_city': request.POST['town_or_city'],
'street_address1': request.POST['street_address1'],
'street_address2': request.POST['street_address2'],
'county': request.POST['county'],
}
token = request.POST['stripeToken']
form = SubscriptionForm(form_data)
if form.is_valid():
customer = stripe.Customer.retrieve(
user_membership.stripe_customer_id)
customer.source = token
customer.save()
subscription = stripe.Subscription.create(
customer=user_membership.stripe_customer_id,
items=[
{"plan": selected_membership.stripe_plan_id},
]
)
user_membership = get_user_membership(request)
selected_membership = get_selected_membership(request)
user_membership.membership = selected_membership
user_membership.save()
form.save(commit=True)
subscription_id = subscription.id
sub, created = Subscription.objects.get_or_create(
user_membership=user_membership)
sub.stripe_subscription_id = subscription_id
sub.active = True
sub.save()
try:
del request.session['selected_membership_type']
except BaseException:
pass
return render(request, 'memberships/update-success.html')
else:
return redirect(reverse('membership_list'))
context = {
'selected_membership': selected_membership,
'form': form,
}
return render(request, 'memberships/payment.html', context)
When the form.save() is the line above the return(render) line, it will process everything as normal, and the form information just wont save into the DB.
It flashes the NOT NULL error when the form.save() line is where it in in the code above.
Any ideas how to get this working?
Thanks!
EDIT: Here's a link to the entire error in Django - http://dpaste.com/140VD8M
& a screenshot of it too!
Here's my models -
class Membership(models.Model):
membership_type = models.CharField(
choices=MEMBERSHIP_CHOICES,
default='Free',
max_length=30)
price = models.IntegerField(default=15)
description = models.TextField(default="DESCRIPTION")
image_url = models.URLField(max_length=1024, null=True, blank=True)
image = models.ImageField(null=True, blank=True)
stripe_plan_id = models.CharField(max_length=40)
def __str__(self):
return self.membership_type
class UserMembership(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
full_name = models.CharField(max_length=50, null=True, blank=True)
email = models.EmailField(max_length=254, null=True, blank=True)
phone_number = models.CharField(max_length=20, null=True, blank=True)
country = CountryField(blank_label='Country', default="Ireland")
postcode = models.CharField(max_length=20, null=True, blank=True)
town_or_city = models.CharField(max_length=40, null=True, blank=True)
street_address1 = models.CharField(max_length=80, null=True, blank=True)
street_address2 = models.CharField(max_length=80, null=True, blank=True)
county = models.CharField(max_length=80, null=True, blank=True)
stripe_customer_id = models.CharField(max_length=40)
membership = models.ForeignKey(
Membership, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.user.username
def post_save_usermembership_create(
sender, instance, created, *args, **kwargs):
user_membership, created = UserMembership.objects.get_or_create(
user=instance)
if user_membership.stripe_customer_id is None or user_membership.stripe_customer_id == '':
new_customer_id = stripe.Customer.create(email=instance.email)
free_membership = Membership.objects.get(membership_type='Free')
user_membership.stripe_customer_id = new_customer_id['id']
user_membership.membership = free_membership
user_membership.save()
post_save.connect(post_save_usermembership_create,
sender=settings.AUTH_USER_MODEL)
class Subscription(models.Model):
user_membership = models.ForeignKey(
UserMembership, on_delete=models.CASCADE)
stripe_subscription_id = models.CharField(max_length=40)
active = models.BooleanField(default=False)
def __str__(self):
return self.user_membership.user.username
& here's my user membership def -
#login_required()
def get_user_membership(request):
user_membership_qs = UserMembership.objects.filter(user=request.user)
if user_membership_qs.exists():
return user_membership_qs.first()
return None
Instead of collecting all the form fields individually, you should be able to just pass the request.POST to the form like so:
form_data = request.POST
token = request.POST['stripeToken']
form = SubscriptionForm(form_data)
Other than that, without seeing the exact error message, there isn't much more to tell. If you update your question I will update my answer.
EDIT:
Without seeing your model and what get_user_membership() returns, it looks like you are missing a User object in a UserMembership class (but I can't tell without seeing more):
user_membership.user = request.user
Or something like that.

Django - Saving object worked one time but now it doesnt

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})

Cannot assign "<SimpleLazyObject: <User: admin>>": "Project.manager" must be a "Profil" instance

Hello I have this error when I start saving a form.
Cannot assign "<SimpleLazyObject: <User: admin>>": "Project.manager" must be a "Profil" instance.
I have two applications account and project
account.model.py
class Profil(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
photo_path = time.strftime('photo/%Y/%m/%d')
photo = models.ImageField(upload_to=PathAndRename(photo_path), blank=True, null=True)
antity = models.CharField(max_length=50, choices=ENTITY_TYPE, default=ENTITY_TYPE[0])
biography = models.TextField(blank=True, max_length=500)
location = models.CharField(max_length=30, blank=True, default='Congo-BZV')
facebook_url = models.URLField(default='', blank=True)
twitter_url = models.URLField(default='', blank=True)
inscrit_newsletter = models.BooleanField(default=True)
def __str__(self):
return "Profil de {0}".format(self.user.username)
project.model.py
class Project( models.Model):
manager = models.ForeignKey('accounts.Profil', related_name='project', on_delete=models.CASCADE)
title = models.CharField(max_length = 100)
slug = models.SlugField(unique=True)
image_path = time.strftime('images/%Y/%m')
main_image = models.ImageField(upload_to=PathAndRename(image_path), blank=True)
slogan = models.CharField(max_length=300, blank=True)
description = RichTextUploadingField(blank = True, null=True)
project.views.py
def project_new(request):
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
project = form.save(commit = False)
project.manager = request.user
project.save()
else:
form = ProjectForm()
return render(request, 'project/project_new.html', {'form': form})
project.forms.py
class ProjectForm(forms.ModelForm):
title = forms.CharField(label='Titre')
description = forms.CharField(widget=CKEditorUploadingWidget())
category = forms.ModelChoiceField(queryset = Category.objects.all(), label='Catégorie')
#description = forms.CharField(widget=forms.Textarea(attrs={'cols': 80, 'rows': 20}))
class Meta:
model = Project
fields = ('title', 'nb_days', 'slogan', 'category', 'description')
I would like every user or manager to be linked to the project they post via a form.
How could I link the two models by saving a model?
Thank you
insted of
project.manager = request.user
you should use:
project.manager = request.user.profil

KeyError at /partners/create/ 'name'

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 :)