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.
Related
I’m trying to create a category for each post.
I made another class with the same models.py and in the same class Post I made a category = models.ForeignKey
But it keeps showing me this error when I run the server:
(no such column: Blog_post.category_id)
Ps: I did run the makemigrations and the migrate command.
The tutorial I followed just added the model as it is in models.py but should I also make a function for the views.py or its just a model problem ?
models.py
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Post(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE, default="Some random thing")
werkstoffnummer = models.CharField(max_length=100)
def __str__(self):
return self.werkstoffnummer
def get_absolute_url(self):
return reverse("post-detail", kwargs={"pk": self.pk})
views.py
from random import choices
from unicodedata import category
from django import forms
from django.shortcuts import get_object_or_404, render, get_list_or_404, HttpResponse
from django.conf import settings
from django.http import HttpResponse, Http404
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User
from django.views.generic import (ListView, DetailView, CreateView, UpdateView, DeleteView)
from .models import Post, Category
from django.db.models import Q
import pandas as pd
import json
import os
def home(request):
context = {"posts": Post.objects.all()}
return render(request, "Blog/home.html", context)
def werkstoffdaten(request):
context = {"posts": Post.objects.all()}
return render(request, "Blog/werkstoffdaten.html", context)
class PostListView(ListView):
model = Post
template_name = "Blog/werkstoffdaten.html" # <app>/<model>_<viewtype>.html
context_object_name = "posts"
ordering = \["-date_posted"\]
paginate_by = 100
class PostListView(ListView):
model = Post
template_name = "Blog/home.html" # <app>/<model>_<viewtype>.html
context_object_name = "posts"
ordering = \["-date_posted"\]
paginate_by = 100
class UserPostListView(ListView):
model = Post
template_name = "Blog/user_posts.html" # <app>/<model>_<viewtype>.html
context_object_name = "posts"
paginate_by = 100
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get("username"))
return Post.objects.filter(author=user).order_by("-date_posted")
class PostDetailView(DetailView):
model = Post
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
fields = \[
"werkstoffnummer", "werkstoffbezeichnung",
\]
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Post
fields = \[
"werkstoffnummer", "werkstoffbezeichnung",
\]
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Post
success_url = "/"
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
def Periodic_Table(request):
return render(request, "Blog/Periodic_Table.html")
def user_manual(request):
return render(request, "Blog/user_manual.html")
def about(request):
return render(request, "Blog/about.html", {"title": "About"})
def search_post(request):
if request.method == "POST":
searched = request.POST.get("searched")
posts = Post.objects.filter(
Q(werkstoffnummer=searched) | Q(werkstoffbezeichnung=searched) | Q(gruppe=searched)
)
return render(
request, "Blog/search_post.html", {"searched": searched, "posts": posts}
)
else:
return render(request, "Blog/search_post.html", {})
def download(request, path):
file_path = os.path.join(settings.MEDIA_ROOT, path)
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
response\['Content-Disposition'\] = 'inline; filename=' + os.path.basename(file_path)
return response
raise Http404
OperationalError at /
https://imgur.com/a/lVDedeq
Delete default="Some random thing" in your category field, default value for foreign key of your Category model, must be a private key (pk (aka id (type == integer))), but not the string.
If you just delete this default value, it will work, or you can put default=1 as first object of your Category models would be default for your new Post objects
class Post(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
or
class Post(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1)
I am quite new to software development and quite new to django and python. I am currently working on a project to develop blog, which needs to have functions for users to edit and delete their own comments.
Whilst I have developed the blog, I am struggling with getting the functions correctly coded and wired up to URLS file.
I have added icons below user comments to either delete or edit their comments.
My question is what is the correct code for creating functions in views file and also how can i correctly wire it up to URL file. I am not sure if I am missing any packages to get the edit/delete functionality developed.
I have enclosed details of my model, views and urls files.
Any guidance/support will be highly appreciated.
Models file
from django.db import models
from django.contrib.auth.models import User
from cloudinary.models import CloudinaryField
STATUS = ((0, "Draft"), (1, "Published"))
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_posts")
updated_on = models.DateTimeField(auto_now=True)
content = models.TextField()
featured_image = CloudinaryField('image', default='placeholder')
excerpt = models.TextField(blank=True)
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
likes = models.ManyToManyField(User, related_name='blog_likes', blank=True)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
def number_of_likes(self):
return self.likes.count()
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
name = models.CharField(max_length=80)
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
approved = models.BooleanField(default=False)
class Meta:
ordering = ['-created_on']
def __str__(self):
return f"Comment {self.body} by {self.name}"
Views file
from django.shortcuts import render, get_object_or_404, reverse
from django.views import generic, View
from django.http import HttpResponseRedirect
from .models import Post
from .forms import CommentForm
class PostList(generic.ListView):
model = Post
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'index.html'
paginate_by = 4
class PostDetail(View):
def get(self, request, slug, *args, **kwargs):
queryset = Post.objects.filter(status=1)
post = get_object_or_404(queryset, slug=slug)
comments = post.comments.filter(approved=True).order_by("-created_on")
liked = False
if post.likes.filter(id=self.request.user.id).exists():
liked = True
return render(
request,
"post_detail.html",
{
"post": post,
"comments": comments,
"commented": False,
"liked": liked,
"comment_form": CommentForm()
},
)
def post(self, request, slug, *args, **kwargs):
queryset = Post.objects.filter(status=1)
post = get_object_or_404(queryset, slug=slug)
comments = post.comments.filter(approved=True).order_by("-created_on")
liked = False
if post.likes.filter(id=self.request.user.id).exists():
liked = True
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
comment_form.instance.email = request.user.email
comment_form.instance.name = request.user.username
comment = comment_form.save(commit=False)
comment.post = post
comment.save()
else:
comment_form = CommentForm()
return render(
request,
"post_detail.html",
{
"post": post,
"comments": comments,
"commented": True,
"liked": liked,
"comment_form": CommentForm()
},
)
class PostLike(View):
def post(self, request, slug):
post = get_object_or_404(Post, slug=slug)
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
else:
post.likes.add(request.user)
return HttpResponseRedirect(reverse('post_detail', args=[slug]))
Urls file
from . import views
from django.urls import path
urlpatterns = [
path("", views.PostList.as_view(), name="home"),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
path('like/<slug:slug>', views.PostLike.as_view(), name='post_like'),
]
As you are using class based views, there are generic views already set up for Updating and Deleting: See the docs https://docs.djangoproject.com/en/4.0/ref/class-based-views/generic-editing/
Your icons can simply be links to those views, and the rest is handled for you. You don't need to add complexity to your PostDetails view.
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)
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']
I have a django form which takes a paramater from the view to initialize the MultipleChoiceField based on the user instance.
The form is working fine when loading the template.
when i submit the form the init method in the form raising an error.
My Model models.py
from django.db import models
from django.contrib.auth.models import User
class Group(models.Model):
group_name = models.CharField('Group name', max_length=50)
def __str__(self):
return self.group_name
class GroupMembers(models.Model):
group_name = models.ManyToManyField(Group)
members = models.ForeignKey(User, on_delete=models.CASCADE)
class Transactions(models.Model):
bill_type = models.CharField('Bill type',max_length=200)
added_by = models.ForeignKey(GroupMembers, on_delete=models.CASCADE)
added_to = models.ForeignKey(Group, on_delete=models.CASCADE)
purchase_date = models.DateField(auto_now=True)
share_with = models.CharField('Share among',max_length=250)
amount = models.IntegerField(default=0)
def __str__(self):
return self.bill_type
forms forms.py
from django import forms
from .models import Transactions, GroupMembers
class Bill_CreateForm(forms.ModelForm):
def __init__(self, user_list, *args, **kwargs):
super(Bill_CreateForm, self).__init__(*args, **kwargs)
self.fields['share_with'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=tuple([(name, name.members) for name in user_list]))
class Meta:
model = Transactions
fields = (
'bill_type',
'amount',
'added_by',
'added_to',
'share_with',
)
** RESOLVED MY ISSUE WITH THE HELP OF #Alasdair "
EDITED SOLUTION
views views.py
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from .models import Transactions, Group, GroupMembers
from .forms import Bill_CreateForm
from django.http import HttpResponse, HttpResponseRedirect
def add_bills_home(request, id=None):
user = User.objects.get(pk=id)
grpname = Group.objects.filter(groupmembers__members=user)
gm = GroupMembers.objects.filter(group_name__group_name=grpname[0])
users_list = [i for i in gm]
if request.method == 'POST':
form = Bill_CreateForm(users_list, request.POST)
if form.is_valid():
print(form.cleaned_data['share_with'])
form.save()
form = Bill_CreateForm(users_list)
return render(request, 'bills/create_bill.html', {'form':form})
else:
form = Bill_CreateForm(users_list)
return render(request, 'bills/create_bill.html', {'form':form})
The error is
After submiting the form with data
the request.POST method returning
below data
i don't know if the request.POST method re-initializes the form with the filled data and pass it to the init method in the form.py.
Please help me with this