Im trying using class modelForm in django - python

My models.py:
from django.db import models
# Create your models here.
class modelBlog(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
body = models.TextField()
pub_date = models.DateTimeField(auto_now_add=True,)
def __str__(self):
return ('{}.{}').format(self.id, self.title)
class comment(models.Model):
blog = models.ForeignKey(modelBlog, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
komentar = models.TextField()
pub_date = models.DateTimeField(auto_now_add=True,)
My forms.py:
from .models import modelContact, comment
from django import forms
class CommentForm(forms.ModelForm):
class meta:
model = comment
fields = [
'name',
'komentar',
]
widgets = {
'name': forms.TextInput(attrs={'class':'form-control'}),
'komentar': forms.Textarea(attrs={'class':'form-control'}),
}
And views.py:
def detail(request, id):
blog = modelBlog.objects.get(id=id)
form = CommentForm()
if request.method == 'POST':
nama = request.POST['nama']
comment = request.POST['komentar']
new_comment = blog.comment_set.create(name=nama,komentar=comment)
new_comment.save()
messages.success(request, 'Komentar berhasil ditambahkan')
return redirect('blog:detail', id)
judul = blog.title
context = {
'title':judul,
'blog':blog,
'form':form
}
return render(request, 'blog/detail.html', context)
i got error
ValueError at /blog/1/
ModelForm has no model class specified.
Request Method: GET
Request URL: http://localhost:8000/blog/1/
Django Version: 4.0.2
Exception Type: ValueError
Exception Value:
ModelForm has no model class specified.

I think, you have written meta in smallcase, write it in Pascal case that is Meta and write all your models in PascalCase such as Comment etc.

Related

How set username to ForeignKey

I want to set value, but i don't know how do it.
Error:
RelatedObjectDoesNotExist at /comments/
commentsTabl has no avtor.
Request Method: GET
Request URL: http://localhost:8000/comments/
Django Version: 4.0.2
Exception Type: RelatedObjectDoesNotExist
Exception Value:
commentsTabl has no avtor.
Exception Location: D:\python39\lib\site-packages\django\db\models\fields\related_descriptors.py, line 197, in get
Python Executable: D:\python39\python.exe
Python Version: 3.9.6
Python Path:
['D:\Django\ForumXT\first',
'D:\python39\python39.zip',
'D:\python39\DLLs',
'D:\python39\lib',
'D:\python39',
'D:\python39\lib\site-packages']
Server time: Thu, 07 Apr 2022 12:20:35 +0000
models.py
class commentsTabl(models.Model):
Text = models.TextField(verbose_name='Text')
date = models.DateTimeField(default=timezone.now, verbose_name='date')
avtor = models.ForeignKey(User, verbose_name='avtor', on_delete=models.CASCADE, to_field="username")
def __str__(self):
return f'Comment {self.avtor} at {self.date}'
class Meta:
verbose_name = "Comment"
verbose_name_plural = "Comments"
views.py
def comments(request):
data = {
'com': reversed(commentsTabl.objects.all())
}
if request.method =="POST":
form = commentsTabl(request.POST)
if form.is_valid():
form.save()
else:
form = commentsTabl()
return render(request, 'home/comments.html', data, {'form':form})
In models.py
class Comment(models.Model):
Text = models.TextField(verbose_name='Text')
date = models.DateTimeField(auto_add_now=True, verbose_name='date')
avtor = models.ForeignKey(User, verbose_name='avtor', on_delete=models.CASCADE)
def __str__(self):
return 'Comment {} at {}'.format(self.avtor, self.date)
class Meta:
# Order comments in reverse order
# ordering = ["-id"]
In views.py
from .forms import CommentForm
from .models import Comments
from django.http import HttpResponseRedirect
from django.urls import reverse
def comments(request):
# Retrive all comments from database
comments = Comment.objects.all()
# Reverse ...
comments = reversed(comments)
# Form with no data (unbound form)
form = CustomerForm()
context = {"comments": comments, "form": form}
# when method is post
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
# Don't save the form to database
comment = form.save(commit=False)
# Add user to the comment
comment.avtor = request.user
# Save comment to database
comment.save()
return HttpResponseRedirect(reverse('some url name'))
# when form is invalid
else:
# Re-render the form with errors and data
context["form"] = form
return render(request, "home/comments.html", context)
# when method is not post
else:
return render(request, "home/comments.html", context)
In forms.py
from django.forms import ModelForm
from .models import Comment
# Create your forms here
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ("Text", "date",)
# or
# exclude = ("avtor",)
# fields = "__all__"
Important
python manage.py makemigrations
python manage.py migrate
In comments.html you will have access to form and comments

'ReverseManyToOneDescriptor' object has no attribute 'filter'

'ReverseManyToOneDescriptor' object has no attribute 'filter'
why?)
I'm trying to create a blog in django, got to the stage of adding comments and categories and got stuck
I get an error.
views.py
from django.shortcuts import render,
get_object_or_404
from .models import Post, Comment
from django.views import generic
from django.http import HttpResponse
from .forms import CommentForm
def blog_list(request):
post = Post.objects.all().order_by('-date')
return render(request,'blog/blog_list.html', {'posts':post})
def blog_detail(request, slug):
#return HttpResponse(slug)
detail_post = Post.objects.get(slug=slug)
comments = Post.comments.filter(active=True)
new_comment = None
# Comment posted
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
return render(request,'blog/blog_detail.html', {'detail_post':detail_post, 'comments':comments, 'new_comment': new_comment, 'comment_form': comment_form})
I hope someone helps, also with the problem of adding a category
14.comments = Post.comments.filter(active=True) …
▶ Local vars
here is my
models.py
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField()
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
first_src = models.CharField('первоисточник', blank=True, max_length=100)
author = models.ForeignKey(User, on_delete= models.CASCADE )
thumb = models.ImageField(default='default.png', blank=True)
# add AND GO TO MIGRATE AND MAKEMIGRATIONS !!!
class Meta:
ordering = ['-date']
def __str__(self):
return self.title
def snippet(self):
return self.body[:50]+'...'
"""def get_absolute_url(self):
from django.urls import reverse
return reverse("post_detail", kwargs={"slug": str(self.slug)})"""
class Comment(models.Model):
post = models.ForeignKey(Post,
on_delete=models.CASCADE,
related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
class Meta:
ordering = ('created',)
def __str__(self):
return 'Comment by {} on {}'.format(self.name, self.post)
What's wrong?
I hope someone helps, also with the problem of adding a category
You're trying to filter on the class (Post), but want to filter on the specific model (detail_post):
comments = detail_post.comments.filter(active=True)

NOT NULL constraint failed: community_comment.posts_id?

how can I fix this issue?
the page runs perfectly. when I do post the post. it posts but when I want to type the comment and send by 'GET' I get this error. so, how can I ignore this error this my first question?
- also, I need anyone to give me the best way to make a relationship between post and comment
models.py
from django.db import models
from django.contrib.auth.models import User
class Publication(models.Model):
title = models.CharField(max_length=30)
class Meta:
ordering = ['title']
def __str__(self):
return self.title
class Article(models.Model):
publications = models.ManyToManyField(Publication)
headline = models.CharField(max_length=100)
class Meta:
ordering = ['headline']
def __str__(self):
return self.headline
class Post(models.Model):
users = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
question = models.TextField(max_length=500)
def __str__(self):
return self.title
class Comment(models.Model):
posts = models.ForeignKey(Post, on_delete=models.CASCADE)
comment = models.TextField(max_length=500)
def __str__(self):
return self.comment
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from .models import Post, Comment
from .forms import PostForm, CommentForm
def index(request):
# All questions
posts = Post.objects.all()
return render(request, 'community/index.html', {'posts': posts})
def post_view(request):
post_form = PostForm
context = {'posted': post_form}
# Create post
if request.method == 'GET':
post_form = PostForm(request.GET)
if post_form.is_valid():
user_post = post_form.save(commit=False)
user_post.title = post_form.cleaned_data['title']
user_post.question = post_form.cleaned_data['question']
post = Post.objects.create(users=User.objects.get(username=request.user), title=user_post.title, question=user_post.question)
post.save()
return redirect('community:index')
return render(request, 'community/post.html', context)
def answers(request, post_id):
# Specific post
posts = Post.objects.get(id=post_id)
# Create comment
comment_form = CommentForm
context = {'posts': posts, 'comment_form': comment_form}
if request.method == 'GET':
comment_form = CommentForm(request.GET)
if comment_form.is_valid():
user_comment = comment_form.save(commit=False)
user_comment.comment = comment_form.cleaned_data['comment']
user_comment.save()
return render(request, 'community/answers.html', context)
urls.py
from django.urls import path
from . import views
app_name = 'community'
urlpatterns = [
path('', views.index, name='index'),
path('post/', views.post_view, name='post'),
path('answers/<int:post_id>', views.answers, name='answers'),
]
forms.py
from .models import Post, Comment
from django import forms
from django.contrib.auth.models import User
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = '__all__'
exclude = ['users']
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = '__all__'
exclude = ['users', 'posts']
You forgot to assign the post, or the post_id of the comment you created:
def answers(request, post_id):
# Specific post
posts = Post.objects.get(id=post_id)
# Create comment
comment_form = CommentForm
context = {'posts': posts, 'comment_form': comment_form}
if request.method == 'GET':
comment_form = CommentForm(request.GET)
if comment_form.is_valid():
comment_form.instance.post_id = post_id
user_comment = comment_form.save()
# …
That being said, the above view does not really respect the HTTP assumptions. A view that makes a GET request is not supposed to change entities, so if you want to create a comment, you need to do that through a POST request. Furthemore in order to implement the Post/Redirect/Get pattern [wiki] a successful POST request should return a redirect response.

error in Django RestFrameWork "NOT NULL constraint failed: qoura_question.author_id "

trying to add a post to DRF which takes the information of USER and TIME automatically, But this is the error which pops up when tried to add a Post.
models.py:
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class Post(models.Model):
title = models.CharField(max_length = 200)
description = models.CharField(max_length = 2000)
date_posted = models.DateTimeField(default = timezone.now)
author = models.ForeignKey(User , on_delete = models.CASCADE)
def __str__(self):
return self.title
Views.py:
class PostViewSet(ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
authentication_classes = [TokenAuthentication,SessionAuthentication]
def create(self, request):
obj = Post()
obj.title = request.data['title']
obj.description = request.data['description']
obj.date_posted = request.data['date_posted']
obj.user = request.user
obj.save()
return Response(status=status.HTTP_201_CREATED)
serializer.py:
from rest_framework import serializers
from django.contrib.auth.models import User
from . models import Post
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ('id', 'title','description','date_posted','author')

Filtering the options of ModelChoiceField in forms in django as per the ForeignKey relations

In my django project, I created three model classes. The class 'Subtopic' has ForeignKey relation with class 'Chapter' and class 'SAQ' has ForeignKey relation with class 'Chapter' and class 'Subtopic'.
#models.py
from django.db import models
class Chapter(models.Model):
chapter_serial = models.IntegerField(null=False, help_text="Chapter No.")
slug = models.SlugField(unique=True, blank=True)
chapter_name = models.CharField(max_length=120)
class Meta:
ordering = ["chapter_serial"]
def get_saq_list_url(self):
return reverse("cms:saq_list", kwargs={"chap_slug":self.slug})
class Subtopic(models.Model):
subtopic_serial = models.IntegerField(null=False)
title = models.CharField(max_length=240)
chapter = models.ForeignKey('Chapter', on_delete=models.CASCADE)
class Meta:
ordering = ["subtopic_serial"]
class SAQ(models.Model):
question_serial = models.IntegerField(null=False)
question = models.TextField()
answer = models.TextField()
chapter = models.ForeignKey('Chapter', on_delete=models.CASCADE)
subtopic = models.ForeignKey('Subtopic', on_delete=models.CASCADE, null=True, blank=True)
class Meta:
ordering = ["question_serial"]
I tried to create forms using django ModelForm for 'model SAQ' such that for each 'SAQ form' associated with a particular chapter instance, the choice field for model 'Subtopic' will contain only those subtopics of that particular chapter instance.
#forms.py
from django import forms
from .models import SAQ
class SAQForm(forms.ModelForm):
class Meta:
model = SAQ
fields = [
'question_serial',
'question',
'answer',
'important',
'remarks',
'subtopic',
]
The django view function to create the form is as below.
from django.shortcuts import render, get_object_or_404, redirect
from .models import SAQ, Chapter, Subtopic
from .forms import SAQForm
from django.http import HttpResponseRedirect
def saq_create(request, chap_slug=None):
chapter_instance = get_object_or_404(Chapter, slug=chap_slug)
form = SAQForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.chapter = chapter_instance
instance.save()
return HttpResponseRedirect(chapter_instance.get_saq_list_url())
context = {
"form":form,
"chapter_instance":chapter_instance,
}
return render(request, 'cms/saq_form.html', context)
With this configuration, the choice field in the form, for 'Subtopic' shows all subtopics for all chapter instances. Any suggestion would be very helpful.
I would suggest to override the form init and pass the chapter instance so you can filter the subtopic queryset.
Example (not tested, could contain typos):
#forms.py
from django import forms
from .models import SAQ
class SAQForm(forms.ModelForm):
class Meta:
model = SAQ
fields = [
'question_serial',
'question',
'answer',
'important',
'remarks',
'subtopic',
]
def __init__(self, chapter, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['subtopic'].queryset = \
self.fields['subtopic'].queryset.filter(chapter=chapter)
And then your view should pass the chapter instance to the form:
chapter_instance = get_object_or_404(Chapter, slug=chap_slug)
form = SAQForm(chapter_instance, request.POST or None)

Categories

Resources