I cannot submit the comments for multi posts in Django - django

I have a feed and in this feed have posts and each post have comments, Now I can submit a comment for just the first post but when I try to come to the second or third post and submit comment this error rise
ValueError: The view videos.views.add_comment_post didn't return an HttpResponse object. It returned None instead.
I thought that the problem with the posts id conflict with each other so I passed all the comment fields to the template and the same error still happen. "this problem happen with any post except the first one"
My comments view
comment_form = PostCommentForm(request.POST )
if comment_form.is_valid():
user_comment = comment_form.save(commit=False)
user_comment.author = request.user
user_comment.save()
result = comment_form.cleaned_data.get('content')
user = request.user.username
return JsonResponse({'result': result, 'user': user})
My Post model
class Post(models.Model):
author = models.ForeignKey(Account, on_delete=models.CASCADE)
article = models.TextField(null=True, blank=True)
photo_article = models.ImageField(max_length=255, upload_to=get_poster_filepath)
created_date = models.DateTimeField(auto_now_add=True)
My comments model
class PostCommentIDE(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='ide_com')
author = models.ForeignKey(Account, on_delete=models.CASCADE)
content = models.TextField()
created_date = models.DateTimeField(auto_now_add=True)
My comments Form
class PostCommentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class Meta:
model = PostCommentIDF
fields = {'post', 'content'}
widgets = {
'content': forms.Textarea(attrs={'class': 'rounded-0 form-control', 'rows': '1', 'placeholder': 'Comment', 'required': 'True', })
}
def save(self, *args, **kwargs):
PostCommentIDF.objects.rebuild()
return super(PostCommentForm, self).save(*args, **kwargs)

when form is not valid the form is returning None.
you should return something(for example returning error messages) when form is not valid.
comment_form = PostCommentForm(request.POST)
if comment_form.is_valid():
user_comment = comment_form.save(commit=False)
user_comment.author = request.user
user_comment.save()
result = comment_form.cleaned_data.get('content')
user = request.user.username
return JsonResponse({'result': result, 'user': user})
else:
# do stuff here if form is not valid
return JsonResponse({'result': 'Something went wrong.'})

Related

NOT NULL constraint failed: cms_viewcount.session

I am trying to get users ip address for a blog project view counts, and when the user isn't logged in a get this error
integrityError at /article/another-post-to-test-things-out/
NOT NULL constraint failed: cms_viewcount.session
Here is my views.py
# regular blog details
def blog_detail(request, slug):
template_name = 'cms/single.html'
blog = Blog.objects.get(slug=slug)
msg = False
form = CommentForm()
ip=request.META['REMOTE_ADDR']
if not ViewCount.objects.filter(blogview=blog, session=request.session.session_key):
view=ViewCount(blogview=blog, ip_address=ip, session=request.session.session_key)
view.save()
blog_views=ViewCount.objects.filter(blogview=blog).count()
if request.user.is_authenticated:
user = request.user
if blog.likes.filter(id=user.id).exists():
msg = True
context = {'blog': blog, 'msg':msg, 'form':form, "view_count":blog_views,}
try:
if request.method == 'POST':
form = CommentForm(request.POST)
comment = form.save(commit=False)
comment.blog = blog
comment.owner = request.user
comment.save()
messages.success(request, 'Your review was successfully submitted!')
return redirect('blog-detail', slug=blog.slug)
if not request.user or not request.user.is_authenticated:
return render(request, template_name, context)
else:
return render(request, template_name, context)
except:
return render(request, "cms/login-prompt.html", context)
Here is the error on my browser also
view.save() …
Local vars
Variable Value
blog
<Blog: Another Post to test things out>
form
<CommentForm bound=False, valid=Unknown, fields=(body)>
msg
False
request
<WSGIRequest: GET '/article/another-post-to-test-things-out/'>
slug
'another-post-to-test-things-out'
template_name
'cms/single.html'
view
<ViewCount:>
PLease how can I fix this error , note everthing works fine when the user is logged in
models.py
#views count models
class ViewCount(models.Model):
blogview=models.ForeignKey(Blog, related_name="view_count", on_delete=models.CASCADE)
ip_address=models.CharField(max_length=50)
session=models.CharField(max_length=50)
def __str__(self):
return str(self.ip_address)
#comment model
class Comment(models.Model):
owner= models.ForeignKey(User, on_delete=models.CASCADE, null=True)
blog= models.ForeignKey(Blog, on_delete=models.CASCADE)
body = models.TextField(null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True,editable=False)
class Meta:
ordering = ['-created']
def __str__(self):
return str(self.blog)
forms.py if need be
#comment form
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['body']
labels = {
'body': 'Add a comment'
}
def __init__(self, *args, **kwargs):
super(CommentForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs.update({'class': 'input'})
Here is the error again
IntegrityError at /article/another-post-to-test-things-out/
NOT NULL constraint failed: cms_viewcount.session
You aren't passing the required session argument in this line:
view=ViewCount(blogview=blog, ip_address=ip, session=request.session.session_key)
Since the user isn't logged in, the value is Null.
Allow the value to be Null:
`session=models.CharField(max_length=50, null = True)`
Or generate a session for an anonymous user.

How do i make update function in Django

My project is a discussion forum using Django and here are my create and update functions. The method of update_post should provide update functionality but every time I try to update a post it adds a new post. How can I update a resource?
#login_required
def create_post(request):
context = {}
form = PostForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
print("\n\n its valid")
author = Author.objects.get(user=request.user)
new_post = form.save(commit=False)
new_post.user = author
new_post.save()
form.save_m2m()
return redirect("home")
context.update({
"form": form,
"title": "Create New Post"
})
return render(request, "create_post.html", context)
#login_required
def update_post(request):
context = {}
author = Author.objects.get(user=request.user)
form = PostForm(request.POST , instance=author)
if request.method == "POST":
if form.is_valid():
print("\n\n its valid")
new_post = form.save(commit=False)
# new_post.user = author
new_post.save()
form.save_m2m()
return redirect("home")
context.update({
"form": form,
"title": "UpdatePost",
})
return render(request, "update_post.html", context)
In model total there are 4 classes Post , comment , reply and category and this is Post -
class Post(models.Model):
title = models.CharField(max_length=400)
slug = models.SlugField(max_length=400, unique=True, blank=True)
user = models.ForeignKey(Author, on_delete=models.CASCADE)
content = HTMLField()
categories = models.ManyToManyField(Category)
date = models.DateTimeField(auto_now_add=True)
approved = models.BooleanField(default=True)
hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk',
related_query_name='hit_count_generic_relation'
)
tags = TaggableManager()
comments = models.ManyToManyField(Comment, blank=True)
closed = models.BooleanField(default=False)
state = models.CharField(max_length=40, default="zero")
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
def __str__(self):
return self.title
def get_url(self):
return reverse("detail", kwargs={
"slug":self.slug
})
#property
def num_comments(self):
return self.comments.count()
#property
def last_reply(self):
return self.comments.latest("date")
form = PostForm(request.POST , instance=author)
instance feels like it should be passed an instance of Post instead of an instance of Author. I assume that PostForm is a pretty standard ModelForm with model = Post in the Meta.

Django: Can't update database properly

models.py
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=500, verbose_name='Title')
post = models.TextField(verbose_name='Post')
post_time = models.DateTimeField()
update_time = models.DateTimeField()
exists = models.BooleanField(default=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if not self.id:
self.post_time = timezone.now()
# self.exists = True
self.update_time = timezone.now()
return super(Post, self).save(*args, **kwargs)
class PostEditHistory(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
title = models.CharField(max_length=500)
body = models.TextField()
edit_time = models.DateTimeField()
views.py
#login_required
def edit_post(request, username, post_id):
other_user = User.objects.get(username=username)
post = Post.objects.get(user=other_user.pk, pk=post_id)
prev_post = post
form = EditPostForm(data=request.POST or None, instance=post)
if form.is_valid():
PostEditHistory.objects.create(
user=request.user,
post=prev_post,
title=prev_post.title,
body=prev_post.post,
edit_time=prev_post.update_time
)
return redirect('single_post', username=username, post_id=post_id)
form.save()
context = {
'form': form
}
return render(request, 'blog_post/edit_post.html', context)
Before saving edited post, I'm trying to save the original post to PostEditHistory model. Every time a post is edited, it performs the same operations. But the code save the edited post to both Post and PostEditHistory model, and the original one gets lost. Help me to solve the problem.
Thanks in advance.
You are leaving of your function before use form.save()
return redirect('single_post', username=username, post_id=post_id)
form.save()
Change the position
form.save()
return redirect('single_post', username=username, post_id=post_id)
Suggestion: You should remove logic from views and handle it only in your models using functions...
Obs.: Dont use straight .objects.get() because if this do not exist will break your page and throw error, use filter to get the values without breaking and check it
class PostHistory(models.Model):
...
#staticmethod
def add_history(user, prev_post):
PostEditHistory.objects.create(
user=user,
post=prev_post,
title=prev_post.title,
body=prev_post.post,
edit_time=prev_post.update_time
)
#login_required
def edit_post(request, username, post_id):
...
post = Post.objects.filter(user=other_user.pk, pk=post_id).first()
prev_post = post if post else None
if form.is_valid():
PostEditHistory.add_history(request.user, prev_post)
form.save()
return redirect('single_post', username=username, post_id=post_id)

Qualified input but checked invalid by `form.is_valid`

I input qualified content to form but was checked as invalid by form.is_valid,
Here is my views:
I add print(request.POST) # test input to check posted successfully, and print("form is invalid.") #assert invalid to check if it's a valid form,
class CommentCreateView(View):
template_name = "article/article_detail.html"
def get(self, request, pk):
return redirect(f"/article/detail/{ pk }")
def post(self, request, pk):
self.article = Article.objects.get(id=pk)
form = CommentForm(request.POST)
print(request.POST) # test input
if form.is_valid():
print("form is valid.") #assert valid
comment = form.save(commit=False)
print(f"Comment: {form.cleaned_data}")
comment.owner = request.user
comment.article = self.article
comment.status = 0
comment.save()
return redirect(f"/article/detail/{ pk }")
else:
print("form is invalid.") #assert invalid
comments = (Comment.objects
.filter(article=self.article, status=0)
)
context = {'article': self.article,
'comments':comments,
"form": form}
return render(request, self.template_name, context)
The Comment model data`:
class Comment(models.Model):
STATUS = (
(0, 'normal'),
(-1, 'deleted'),
)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
article = models.ForeignKey(Article, on_delete=models.CASCADE)
comment = models.TextField() # set the widget
status = models.IntegerField(choices=STATUS)
date_created = models.DateTimeField(default=datetime.now)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.comment
And the forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['comment', 'date_created']
widgets = {'comment': forms.Textarea(attrs={'cols': 80})}
The error report:
Django version 1.11.13, using settings 'forum.settings'
Starting development server at http: // 127.0.0.1: 8001/
Quit the server with CONTROL-C.
<QueryDict: {'csrfmiddlewaretoken': ['jL9aDh0cSNgvlmGWtI5sogFlruIvLh4rHqt0jll2V3H70Bel35IDFq6cgkWhAJHK'], 'comment': ['issue a test']} >
form is invalid.
[09/Jun/2018 13:12:32] "POST /article/comment/create/17 HTTP/1.1" 200 4183
It checked that the form is invalid.
How to solve such a problem?

Can't get owner as foreign key to my model -- django

I'm trying to do a form so a user can upload a video, the problem is i can't get current user or it's id as a foreign key on my video model
Error: IntegrityError
Exception Value: (1048, "Column 'owner_id' cannot be null")
How can i solve the problem please, i looked at django documentation but doesn't find answer.
My models.py:
class Videowtm(models.Model):
name = models.CharField(max_length=50, blank=True)
description = models.CharField(max_length=255, blank=True)
uploaded_at = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User)
video = models.FileField(upload_to='videos/')
My forms.py:
class VideowtmForm(forms.ModelForm):
class Meta:
model = Videowtm
fields = ('name', 'description', 'video', )
My views:
#login_required
def model_form_upload(request):
if request.method == 'POST':
form = VideowtmForm(request.POST, request.FILES)
form.owner = request.user
if form.is_valid():
form.save()
return redirect('home')
else:
form = VideowtmForm()
return render(request, 'model_form_upload.html', {
'form': form
})
Try this one:
first add blank=True to the owner in your model:
###No need for this if you don't include it in your form fields###
class Videowtm(models.Model):
name = models.CharField(max_length=50, blank=True)
description = models.CharField(max_length=255, blank=True)
uploaded_at = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User, blank=True)
video = models.FileField(upload_to='videos/')
and then:
views.py:
#login_required
def model_form_upload(request):
if request.method == 'POST':
form = VideowtmForm(request.POST, request.FILES)
if form.is_valid():
video = form.save(commit=False)
video.owner = request.user
video.save()
return redirect('home')
else:
form = VideowtmForm()
return render(request, 'model_form_upload.html', {
'form': form
})