Django save() method not saving to DB - django

What am I doing wrong?
I have two tables, User and Entrepreneur. Objects are not saving in the Entrepreneur table. I even used the shell!
I've deleted the DB and migration files and the error stays the same.
I know similar questions have been asked but I found none fitting my situation.
MY MODELS:
class EntrepreneurProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
mobile = models.CharField(max_length=100, blank=True, null=True)
location = CountryField(blank=True, null=True)
email_notif_on = models.BooleanField(default=False)
photo = models.ImageField(upload_to='photo/%Y/%m/%d', blank=True, null=True)
skills = TaggableManager(blank=True)
date_joined = models.DateField(auto_now_add=True)
accomplishnment = models.ForeignKey(Accomplishment, on_delete=models.CASCADE, null=True, blank=True)
portfolio = models.ManyToManyField(Portfolio, blank=True)
date_of_birth = models.DateField(blank=True, null=True)
url = models.SlugField(unique=True)
def __str__(self):
return f'{self.user}'
def save(self, *args, **kwargs):
if self.url:
self.url = slugify(f'{self.user.first_name} {self.user.last_name} {str(uuid.uuid4()[:7])}')
MY VIEWS:
def signup(request):
if request.method == 'POST':
user_form = UserCreateForm(request.POST)
if user_form.is_valid():
user = user_form.save(commit=False)
user.set_password(user.password)
user.save()
entrep = EntrepreneurProfile.objects.create(user=user)
entrep.save()
print(entrep.id)
return redirect('users:login')
else:
user_form = UserCreateForm()
data = {'user_form': user_form}
return render(request, 'users/signup.html', data)

It seems you forgot to call super().save(*args, **kwargs) in your save method as it is mentioned in
https://docs.djangoproject.com/en/2.2/topics/db/models/#overriding-predefined-model-methods

Related

The view ... didn't return an HttpResponse object. It returned None instead - django

I tried several ways to solve the problem but I couldn't .. every time I got it error. Item added to DB but error message returned on page.
why "get_absolute_url" and "success_url" do not work?
View
class AddItemView(CreateView):
model = Add_Item
form_class = AddItemForm
template_name ='add_item.html'
success_url = reverse_lazy("home")
def form_valid(self, form):
self.object = form.save(commit=False)
# Add_Item.User = User
self.object.user = self.request.user
self.object.save()
Models
class Add_Item(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE, default=None,
null=True)
title = models.CharField(max_length=255)
categories = models.CharField(max_length=255 , choices=all_categories)
description = RichTextField(blank=True,null=True)
condition = models.CharField(max_length=100, choices=cond)
city = models.CharField(max_length=50, choices=cy.city, blank=True)
street = models.CharField(max_length=100, blank=True)
home_number = models.CharField(max_length=100, blank=True)
header_img = models.ImageField(null=True, blank=True, upload_to='img/')
more_img = models.ImageField(null=True, blank=True, upload_to='img/')
Pub_date = models.DateField(auto_now_add=True)
def __str__(self):
return str(self.title)
def get_absolute_url(self):
return reverse('home')
From the docs:
def form_valid(self, form):
# This method is called when valid form data has been POSTed.
# It should return an HttpResponse.
return super().form_valid(form)
You need to add the return line.

Adding a comment section form to my Django app

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)

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 CreateView Object could not be created because the data didn't validate

Good day.
I'm trying to create a object based on form input, i tesed out the data, everything is provided but, for some reason the form is not validated.
I've also tried overriding form_valid(self,form) but the problem with that method was django never went to it as if it didn't exist.
forms.py
class CreatePostForm(forms.ModelForm):
class Meta:
model = Post
fields = '__all__'
views.py
class CreatePost(CreateView):
form_class = CreatePostForm
template_name = 'dashboard/add-product.html'
# success_url = redirect('user_posts:post_detail')
def post(self, request, *args, **kwargs):
form = CreatePostForm(request.POST)
if self.form_valid(form):
post = form.save(commit=False)
post.user = request.user
post.save()
return redirect('user_posts:post_detail', args=post.slug)
print('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')
code in the template is basic form, not gona import it.
data that has been passed via request.POST
user
'b8a3b0b3-0eef-48ed-b257-a6f9bfdd5cda'
title
'theetitle'
main_description
'agdgdfg'
slug
''
main_image
'Bucee_Lee_smile.jpg'
subtitle1
''
sub_description1
''
sub_image1
''
subtitle2
''
sub_description2
''
sub_image2
''
subtitle3
''
sub_description3
''
sub_image3
''
total_likes
''
traceback points to this line
if self.form_valid(form):
model
class Post(models.Model):
id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200, unique=True)
main_description = models.TextField()
slug = models.SlugField(db_index=True, blank=True)
main_image = models.ImageField(upload_to=upload_image)
subtitle1 = models.CharField(max_length=200, blank=True, null=True)
sub_description1 = models.TextField(blank=True, null=True)
sub_image1 = models.ImageField(upload_to=upload_image,
blank=True, null=True)
subtitle2 = models.CharField(max_length=200, blank=True, null=True)
sub_description2 = models.TextField(blank=True, null=True)
sub_image2 = models.ImageField(upload_to=upload_image,
blank=True, null=True)
subtitle3 = models.CharField(max_length=200, blank=True, null=True)
sub_description3 = models.TextField(blank=True, null=True)
sub_image3 = models.ImageField(upload_to=upload_image,
blank=True, null=True)
posts_liked = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='posts_liked',
blank=True, null=True)
total_likes = models.PositiveIntegerField(blank=True, null=True, db_index=True)
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
objects = PostManager()
# TODO: get_absolute_url()
def get_absolute_url(self):
return reverse('user_posts:post_detail', args=[self.slug])
def __str__(self):
return self.title
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
if not self.slug:
self.slug = slugify(self.title)
super(Post, self).save(force_insert, force_update, using, update_fields)
class Meta:
verbose_name_plural = 'Posts'
try the following way
class CreatePost(CreateView):
form_class = CreatePostForm
template_name = 'dashboard/add-product.html'
success_url = ('url_name')
def form_valid(self, form):
valid_data = super(CreatePost, self).form_valid(form)
form.instance.user = self.request.user
return valid_data

OneToOneField is nor related

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