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?
Related
Im trying to handle the existing name of a Category, so that users wont be allowed to create 2 categories with the same name, but at the moment its taking all categories from the database, not only for the logged-in user. I dont know how and where to implement request.user.
I`m building an inventory app where everyone creates their own categories and adds items.
Thank you.
This is my model:
class Category(models.Model):
user = models.ForeignKey(User, default=1, on_delete=models.CASCADE,
related_name='category', null=True)
name = models.CharField(max_length=100, null=False, blank=False)
slug = models.SlugField(max_length=100)
created_on = models.DateTimeField(auto_now_add=True)
timestamp = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-timestamp']
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('category_detail', kwargs={'slug': self.slug})
This is my form:
class CategoryForm(forms.ModelForm):
add_category = forms.BooleanField(widget=forms.HiddenInput, initial=True)
class Meta:
model = Category
fields = ['name']
def clean_name(self):
name = self.cleaned_data.get('name')
if (name == ""):
raise forms.ValidationError('This field cannot be left blank')
for instance in Category.objects.all():
if instance.name == name:
raise forms.ValidationError('There is a category with the name ' + name)
return name
This is my view:
#login_required
def index(request):
categories = Category.objects.filter(user=request.user)
items = Item.objects.all()
add_item = ItemForm()
add_category = CategoryForm()
query = None
if request.method == 'POST':
if 'add_item' in request.POST:
add_item = ItemForm(request.POST)
if add_item.is_valid():
form = add_item.save(commit=False)
form.category = get_object_or_404(
Category, name=request.POST.get('category'),
user=request.user)
add_item.save()
return redirect('home')
else:
add_category = CategoryForm(request.POST)
if add_category.is_valid():
category_form = add_category.save(commit=False)
category_form.save()
messages.success(request, f'{name} has been added')
return redirect('home')
Edit Category View
#login_required
def category_edit(request, pk):
category = Category.objects.get(id=pk)
if request.method == 'POST':
form = CategoryForm(request.POST, instance=category)
if form.is_valid():
form.save()
messages.info(request, f'{category.name} has been updated!')
return redirect('home')
else:
form = CategoryForm(instance=category, user=request.user)
context = {
'form': form,
}
return render(request, 'category_edit.html', context)
Ive tried adding user = request.user in the form class, but that resulted in an error Ive tried adding category_form.user = request.user before saving the form but that was still taking names from every other user
Pass the request's user to the form:
class CategoryForm(forms.ModelForm):
add_category = forms.BooleanField(widget=forms.HiddenInput, initial=True)
def __init__(self, user, *args, **kwargs):
self.user = user
super().__init__(*args, **kwargs)
class Meta:
model = Category
fields = ['name']
def clean_name(self):
name = self.cleaned_data.get('name')
if (name == ""):
raise forms.ValidationError('This field cannot be left blank')
qs = Category.objects.filter(user=self.user, name=name)
if self.instance.pk:
# EXCLUDE CURRENT INSTANCE TO ENABLE EDIT
qs = qs.exclude(pk=self.instance.pk)
if qs.exists():
raise forms.ValidationError('There is a category with the name ' + name)
return name
then in the view you need to pass the user:
#login_required
def index(request):
categories = Category.objects.filter(user=request.user)
items = Item.objects.all()
add_item = ItemForm()
add_category = CategoryForm(user=request.user)
query = None
if request.method == 'POST':
if 'add_item' in request.POST:
add_item = ItemForm(request.POST)
if add_item.is_valid():
form = add_item.save(commit=False)
form.category = get_object_or_404(
Category, name=request.POST.get('category'),
user=request.user)
add_item.save()
return redirect('home')
else:
add_category = CategoryForm(user=request.user, data=request.POST)
if add_category.is_valid():
category_form = add_category.save(commit=False)
category_form.save()
messages.success(request, f'{name} has been added')
return redirect('home')
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.
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.'})
This is my model.
class Project(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(CustomUser, on_delete=models.PROTECT, editable=False)
name = models.CharField(max_length=20)
total = models.DecimalField(max_digits=7, decimal_places=2, default=0)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
comission_owed = models.DecimalField(max_digits=7, editable=False, decimal_places=2, default=0)
comission_paid = models.DecimalField(max_digits=7, editable=False, decimal_places=2, default=0)
def __str__(self):
return self.name
And this is my model form:
class ProjectForm(ModelForm):
required_css_class = 'required'
class Meta:
model = Project
fields = '__all__'
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super().__init__(*args, **kwargs)
self.fields['user'].initial = self.user
and then here's my view:
def add_project(request):
submitted = False
if request.method == "POST":
form = ProjectForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
return HttpResponseRedirect('/add_project/?submitted=True')
else:
form = ProjectForm()
if 'submitted' in request.GET:
submitted = True
return render(request,
'add_project.html',
{'form': form, 'submitted': submitted}
)
I am trying to get the "user" filled by getting the logged in user but when loading the url "add_project/" where the form should load and let me submit I get an error that traces back to
KeyError at /add_project/
'user'
Request Method: GET
Request URL: http://127.0.0.1:8000/add_project/
Django Version: 3.1.2
Exception Type: KeyError
Exception Value:
'user'
Exception Location: /ArtistShop/homepage/forms.py, line 12, in init
Python Executable: /usr/local/bin/python
Python Version: 3.8.6
Python Path:
['/ArtistShop',
'/usr/local/lib/python38.zip',
'/usr/local/lib/python3.8',
'/usr/local/lib/python3.8/lib-dynload',
'/usr/local/lib/python3.8/site-packages']
Server time: Sat, 30 Jan 2021 19:16:12 -0500
You are getting this error because you are not passing the user object to your ProjectForm in the else block.
def add_project(request):
submitted = False
if request.method == "POST":
...
else:
# Here, you should pass the user object too
form = ProjectForm(user=request.user)
...
def add_project(request):
submitted = False
if request.method == "POST":
project = ProjectForm.save(commit=False)
project.user = request.user
else:
.....
you can try this to get the user, and save in projectv.user
My form was working fine but suddenly it stops working and I'm stuck here, help me please!
When I prints form.errors in case of form not valid then it prints
user is a required field.
models.py
class TarWithDocker(models.Model):
name = models.CharField(max_length=255)
user = models.ForeignKey(User, related_name='deployments')
slug = AutoSlugField(populate_from='name', unique=True, name='slug')
archive = models.FileField(upload_to='archives', name='archive')
created_at = models.DateTimeField(default=timezone.now, editable=False)
class Meta:
ordering = ['-created_at']
views.py
class AwdDeployment(LoginRequiredMixin, CreateView):
template_name = 'deployments/awdDeployment.html'
def get(self, request, *args, **kwargs):
return render(request, 'deployments/awdDeployment.html', {})
def post(self, request, *args, **kwargs):
if request.method == 'POST':
form = AwdDeploymentForm(request.POST, request.FILES)
if form.is_valid():
deployment = TarWithDocker()
deployment.name = form.cleaned_data['name']
deployment.user = self.request.user
deployment.archive = form.cleaned_data['archive']
deployment.save()
return HttpResponse("Submitted")
else:
print("not saved")
else:
print("something happnes wrong")
form = AwdDeploymentForm()
return HttpResponseRedirect(reverse('users:deployments:awd'))
You have user in request, but may be not in post data
May be it help you:
post_data = request.POST.copy()
post_data.update({'user': request.user.pk})
form = AwdDeploymentForm(post_data, request.FILES)