NOT NULL constraint failed: blogs_comment.blog_id - python

I'm a beginner at django please help I've been trying to solve it for 2 hours, Thank you so much!
<I got this django error IntegrityError at /blog/431cdef3-d9e7-4abd-bf53-eaa7b188d0fd>
python
#Views
from django.shortcuts import render
from .models import Blog
from .forms import CommentForm
def home(request):
template = 'blogs/home.html'
blogs = Blog.objects.all()
context = {'blogs':blogs}
return render(request, template, context)
def blog(request, pk):
template = 'blogs/blog.html'
blog = Blog.objects.get(pk=pk)
context = {'blog':blog}
if request.method == 'POST':
form = CommentForm(request.POST)
form.save()
else:
form = CommentForm()
context['form'] = form
return render(request, template, context)
#Forms
from django.forms import ModelForm
from .models import Comment
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ['description']
#Models
from django.db import models
import uuid
class Blog(models.Model):
header = models.CharField(max_length=200)
posts = models.TextField(null=True)
footer = models.TextField(null=True, blank=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
def __str__(self):
return self.header
class Comment(models.Model):
blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name='comments')
description = models.TextField(blank=True, null=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
def __str__(self):
return self.description `

Try with this:
def blog(request, pk):
template = 'blogs/blog.html'
blog = Blog.objects.get(pk=pk)
context = {'blog':blog}
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False) # don't save the comment yet
comment.blog = blog # assign the blog
comment.save() # then save
else:
form = CommentForm()
context['form'] = form
return render(request, template, context)
Add the blog to the comment first before committing the comment to the database.

You didn't add with Foreignkey key value. Try this one.
def blog(request, pk):
template = 'blogs/blog.html'
blog = Blog.objects.get(pk=pk)
context = {'blog':blog}
if request.method == 'POST':
form = CommentForm(request.POST, instance=blog)
if form.is_valid():
form.save()
else:
form = CommentForm(instance=blog)
context['form'] = form
return render(request, template, context)

Related

Post matching query does not exist. - Django error while trying to access URL of other pages

Everything was okay till I created a blog app in my Django projects, now when I try to access the other apps(pages) on the website, it gives me this error.
I can't access the URLs under the other apps, I can only access the URLs under the blog
blog/views.py
from django.shortcuts import render, redirect
from .models import Post
from .forms import commentform
def blog(request):
posts = Post.objects.all(pk=id)
return render(request, 'blog.html', {'posts': posts})
def howtouse(request):
return render(request, 'howtouse.html')
def full_post(request, slug):
post = Post.objects.get(slug=slug)
if request.method == 'POST':
form = commentform(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('full_post', slug=post.slug)
else:
form = commentform()
return render(request, 'full_post.html', {'post': post, 'form': form})
blog/models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField()
intro = models.TextField()
body = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-date_added']
class Comments(models.Model):
post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
name = models.CharField(max_length=100)
email = models.EmailField()
body = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['date_added']

Allow the user to input only a part of django model creaton form (add to form after user submitted it)

How I can add data to form that user submitted ? I want the user to fill in the "name" and "done" in the form and automatically add "user" (creator) and "board"
code:
#views.py
#login_required(login_url='loginPage')
def taskAdd(request, pk):
board = Board.objects.filter(user=request.user).get(pk=pk)
form = AddTaskForm()
if request.method == "POST":
form = AddTaskForm(request.POST)
if form.is_valid():
form.initial['user'] = request.user
form.initial['board'] = board
# that doesn't seem to work....
form.save()
return redirect('insideBoard', pk)
context = {'form': form}
return render(request, 'tasks/taskAdd.html', context)
#forms.py
class AddTaskForm(ModelForm):
class Meta:
model = Task
fields = "__all__"
exclude = ('user', 'board',)
#models.py
class Board(models.Model):
title = models.CharField(max_length=50, null=True)
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Task(models.Model):
title = models.CharField(max_length=200, null=True)
done = models.BooleanField(default=False, null=True)
created_at = models.DateTimeField(auto_now_add=True, null=True)
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
board = models.ForeignKey(Board, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.title
You can edit the instance wrapped in the form:
from django.shortcuts import get_object_or_404
#login_required(login_url='loginPage')
def taskAdd(request, pk):
board = get_object_or_404(Board, user=request.user, pk=pk)
form = AddTaskForm()
if request.method == 'POST':
form = AddTaskForm(request.POST)
if form.is_valid():
form.instance.user = request.user
form.instance.board_id = pk
form.save()
return redirect('insideBoard', pk)
context = {'form': form}
return render(request, 'tasks/taskAdd.html', context)
Note: It is often better to use get_object_or_404(…) [Django-doc],
then to use .get(…) [Django-doc] directly. In case the object does not exists,
for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using
.get(…) will result in a HTTP 500 Server Error.

How do I pass the users model as the ForeignKey value while saving a ModelForm in Django?

The models file:
from django.db import models
from django.conf import settings
class Book(models.Model):
rel_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name="Posted By")
title = models.CharField(max_length=256, verbose_name="Title")
description = models.TextField(verbose_name="Description")
price = models.IntegerField(verbose_name="Price")
state = models.CharField(max_length=256, verbose_name="State")
city = models.CharField(max_length=256, verbose_name="City")
neighbourhood = models.CharField(max_length=256, verbose_name="Neighbourhood")
phone = models.IntegerField(verbose_name="Phone Number")
def __str__(self):
return self.title + f" ({self.rel_user.username})"
The forms file:
from django.forms import ModelForm
from Books.models import Book
class BookForm(ModelForm):
class Meta:
model = Book
fields = ['title', 'description', 'price', 'state', 'city', 'neighbourhood', 'phone']
The views file:
from django.shortcuts import render, redirect
from Books.forms import BookForm
from django.contrib import messages
def sell(request):
if request.method == "GET":
form = BookForm()
else:
form = BookForm(request.POST, )
if form.is_valid():
form.save()
messages.success("Successfully added!")
return redirect('sell')
else:
messages.error("Please fill in all the fields.")
return render(request, 'Books/sell.html', {"form": form})
Every time a user submits the form, I want the ForeignKey's value to be filled with that users model. How do I do this?
So suppose user "John" has filled the form. When he clicks submit, the details he enters + his user model should go into the database for that entry.
def sell(request):
if request.method == "POST":
form = BookForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.rel_user = request.user
instance.save()
messages.success("Successfully added!")
return redirect('sell')
else:
messages.error("Please fill in all the fields.")
else:
form = BookForm()
return render(request, 'Books/sell.html', {"form": form}
request.user can be assigned to rel_user as above
You can assign the user to the instance of the form:
from django.shortcuts import render, redirect
from Books.forms import BookForm
from django.contrib import messages
def sell(request):
if request.method == 'GET':
form = BookForm()
else:
form = BookForm(request.POST)
form.instance.rel_user = request.user
if form.is_valid():
form.save()
messages.success('Successfully added!')
return redirect('sell')
else:
messages.error('Please fill in all the fields.')
return render(request, 'Books/sell.html', {'form': form})

Empty django models

Hi I'm getting tottaly empty Comments. And I don't really know why.
Here is my view file.
from django.shortcuts import render, redirect
from .forms import PostForm
from django.views.generic import TemplateView
from .forms import CommentForm
from django.shortcuts import get_object_or_404
from .models import Post
class createPost(TemplateView):
template_name = 'forum/createPost.html'
def get(self, request):
form = PostForm()
return render(request, self.template_name, {'form': form})
def post(self, request):
form = PostForm(request.POST)
if(form.is_valid()):
form.save()
return redirect('/forum')
def add_comment(request, pk):
post = get_object_or_404(Post, pk=pk)
if(request.method == 'POST'):
form = CommentForm(request.POST)
if(form.is_valid()):
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('/forum/')
else:
form = CommentForm()
template = 'forum/addComment.html'
context = {'form': form}
return render(request, template, context)
And here is my models file
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=140)
body = models.CharField(max_length=500)
date = models.DateTimeField()
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comments', null=True, on_delete=models.SET_NULL)
com_title = models.CharField(max_length=140)
com_body = models.CharField(max_length=500)
def __str__(self):
return self.com_title
And lastly here is forms
from django import forms
from .models import Post, Comment
class PostForm(forms.ModelForm):
title = forms.CharField(max_length=140)
body = forms.CharField()
date = forms.DateTimeField()
class Meta:
model = Post
fields = ('title', 'body', 'date')
class CommentForm(forms.ModelForm):
title = forms.CharField(max_length=140)
body = forms.CharField(max_length=500)
class Meta:
model = Comment
fields = ('title', 'body')
I don't really know why I'm getting this error. I get a comment but It is totaly blank. Mabye It has something to do with the comment = form.save(commit=False), but i don't know.
I am really new to Django so please let me know if you know how to solve it. Also if there is somthing more I have to add to this question like urls and stuff please let me know.
Thanks ;)
Try changing your view to
class createPost(CreateView):
template_name = 'forum/createPost.html'
model=Post
form_class=PostForm
def form_valid(self, form):
form.save()
return http.HttpResponseRedirect('/forum')
and then form to
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'body', 'date')
PS: If you don't want to make any changes to your form fields, then form_class is not required. You may provide the fields to the View itself.

django unable to saved forms in database

I'm learning django and I'm trying to save the form using POST method and found its working fine, I'M not able to see the saved message in database(form is not submitted)
Models.py
class Post(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(max_length=10000)
pub_date = models.DateTimeField(auto_now_add=True)
slug = models.SlugField(max_length=200, unique=True)
def __unicode__(self):
return self.title
def description_as_list(self):
return self.description.split('\n')
class Comment(models.Model):
title = models.ForeignKey(Post)
comments = models.CharField(max_length=200)
def __unicode__(self):
return '%s' % (self.title)
Forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'description')
editPostedForm = modelformset_factory(Post, PostForm)
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('comments',)
exclude = ('title',)
Views.py
def detail(request, id):
posts = Post.objects.get(id=id)
comments = posts.comment_set.all()
forms = CommentForm
if request.method == 'POST':
form = CommentForm(request.POST, instance=posts)
print form
if form.is_valid():
form.save(commit=False)
form.save()
else:
print form.errors
else:
form = PostForm()
return render(request, "detail_post.html", {'forms':forms,'posts': posts,'comments':comments})
Why is the post message is not being saved. I got status code 200 in console, also i get the entered data, but the form is not being saved...Any help is much appreciated
I think the problem is that your form excludes title field, but it's required according to Comment definition. You need to give the title to comment instance then save it:
def detail(request, id):
posts = Post.objects.get(id=id)
comments = posts.comment_set.all()
forms = CommentForm
if request.method == 'POST':
form = CommentForm(request.POST,instance=posts)
print form
if form.is_valid():
# create a comment instance in memory first
comment = form.save(commit=False)
# fill out the title field
comment.title = posts
comment.save()
else:
print form.errors
else:
form = PostForm()
return render(request, "detail_post.html", {'forms':forms,'posts': posts,'comments':comments})
Also, I don't know why you use plural form for one instance, like posts should be post because you use objects.get(), make your code more readable would save some confusion for other people.

Categories