Does not display data after filling in the template - python

I make comments on the site and cannot understand why, after the user has filled out comment forms, they are not displayed, I try to display them through a template
P.S
I need to display the text and the nickname that the user would enter
views.py
def CommentGet(request):
if request.method == 'POST':
comment = Comments(request.POST)
name = request.POST['name']
text = request.POST['text']
if comment.is_valid():
comment.save()
return HttpResponseRedirect(request.path_info)
comments = CommentModel.objects.all()
else:
comment = Comments(request.POST)
comments = CommentModel.objects.all()
return render(request, 'news/post.html', {'comment': comment,'comments':comments})
post.html
<form method="post" action="{% url 'comment' %}">
{% csrf_token %}
<input type="text" name="name" value="{{ name }}">
<input type="text" name="text" value="{{ text }}">
<input type="submit">
</form>
{% for comm in comments %}
<h1> {{ comm.name }} </h1>
<h1> {{ comm.text }} </h1>
{% endfor %}
models.py
class CommentModel(models.Model):
name = models.CharField(max_length=100)
text = models.TextField(default='')
dates = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-dates']
def __str__(self):
return self.name

I'd suggest using a ModelForm to make things simpler, Try something like this:
# views.py
def CommentGet(request):
if request.method == 'POST':
comment_form = CommentForm(request.POST)
comment_form.save()
else:
comment_form = CommentForm()
comments = CommentModel.objects.all()
return render(request, 'news/post.html', {'comment_form': comment_form,'comments':comments, })
# forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = CommentModel
fields = ['name', 'text']
Then, in your template, replace the two text fields with {{ comment_form }}

Related

Unable to add comments to a post using a ModelForm in Django

views.py
def postdetail(request,pk): # Single Post view.
post = Post.objects.get(id=pk)
comment = post.comments.all()
comment_count = comment.count()
if request.user.is_authenticated:
if request.method == 'POST':
form = CommentForm(data=request.POST)
content = request.POST['cMessage']
if form.is_valid():
print("Yes valid")
form.instance.body = content
new_comment = form.save(commit=False)
print(new_comment)
new_comment.post = post
new_comment.user = request.user
new_comment.save()
return redirect('blog-home')
else:
form = CommentForm()
context = {
'comment_form': CommentForm,
'post' : post,
'comments': comment,
'count': comment_count,
}
return render(request,'post/postdetail.html', context=context)
models.py
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
user = models.ForeignKey(User,on_delete=models.CASCADE, related_name='comments')
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 f'Comment by {self.user} on {self.post}'
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['body']
template
{% if request.user.is_authenticated %}
<!-- respond -->
<div class="respond">
<h3>Leave a Comment</h3>
<!-- form -->
<form name="contactForm" id="contactForm" method="post" action="">
{% csrf_token %}
<fieldset>
<div class="message group">
<label for="cMessage">Message <span class="required">*</span></label>
<textarea name="cMessage" id="cMessage" rows="10" cols="50" ></textarea>
</div>
<button type="submit" class="submit">Submit</button>
</fieldset>
</form> <!-- Form End -->
</div>
{% endif %}
There is no error being displayed neither If I am adding a comment using the shell/through admin panel but if I am trying to add the comment dynamically through the form then the comment is not getting saved.
I have added only the form in the template.
You have defined field body in your CommentForm. It's required in your form, because you didn't include blank=True argument in your model for this field. This means that when you POST request and check if form is valid with form.is_valid(), the form expects an element with a name body in the request. If it's not there, it will not validate and content won't be saved.
Make the following changes:
Change your view to
...
if request.method == 'POST':
form = CommentForm(data=request.POST)
if form.is_valid():
new_comment = form.save(commit=False)
new_comment.post = post
new_comment.user = request.user
new_comment.save()
return redirect('blog-home')
else:
print(form.errors) # or log it to a file, if you have logging set up
form = CommentForm()
...
Change your HTML to this:
...
<form name="contactForm" id="contactForm" method="post" action="">
{% csrf_token %}
<fieldset>
<div class="message group">
<label for="body">Message <span class="required">*</span></label>
<textarea name="body" id="cMessage" rows="10" cols="50" ></textarea>
{{ comment_form.body.errors }}
</div>
<button type="submit" class="submit">Submit</button>
</fieldset>
</form>
...
In views.py
def postdetail(request):
print(Comment.objects.all())
if request.method == 'POST':
form = CommentForm(data=request.POST)
content = request.POST['body']
if form.is_valid():
print("Yes valid")
new_comment = form.save(commit=False)
print(new_comment)
new_comment.post = post
new_comment.user = request.user
new_comment.save()
return redirect('blog-home')
else:
form = CommentForm()
return render(request,'temp/postdetail.html', context=context)
In html file
{% if request.user.is_authenticated %}
<div class="respond">
<h3>Leave a Comment</h3>
<form name="contactForm" id="contactForm" method="post" action="">
{% csrf_token %}
<textarea name="body"cols="30" rows="10"></textarea>
<button type="submit" class="submit">Submit</button>
</form>
</div>
{% endif %}
This worked for me.

The view students.views.addgrregister didn't return an HttpResponse object. It returned None instead

ValueError at /students/addgrregister/
i am trying to add students in gr_register but its giving an error due to this error the code is not working i also upload the template (addgrregister.html) kndly tell me where is the issue in these pages
models.py
class gr_register(models.Model):
Gender_Choices = (
('M', 'Male'),
('FM', 'Female'),
)
Status_Choices = (
('P', 'Present'),
('FM', 'Left'),
)
gr_no = models.IntegerField(primary_key=True)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
date_birth = models.DateField(null=True)
classes_A = models.ForeignKey(Classes, on_delete=models.CASCADE, related_name="classes_A", default=1, verbose_name="Class of Admission")
sections_A = models.ForeignKey(Sections, on_delete=models.CASCADE, related_name="sections_A", default=1, verbose_name="Section of Admission")
gender = models.CharField(max_length=10, choices=Gender_Choices)
classes_C = models.ForeignKey(Classes, on_delete=models.CASCADE, related_name="classes_C", verbose_name="Current Class")
sections_C = models.ForeignKey(Sections, on_delete=models.CASCADE, related_name="sections_C", verbose_name="Current Section")
address = models.CharField(max_length=100, null=True, verbose_name="Home Address")
area_code = models.ForeignKey(Area, on_delete=models.CASCADE, verbose_name="Area")
status = models.CharField(max_length=10, choices=Status_Choices, default='P')
class Meta:
ordering = ('gr_no',)
def __str__(self):
return self.first_name
views.py
from django.shortcuts import get_object_or_404, render, redirect
def addgrregister(request):
if request.method == 'POST':
form = gr_registerForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
form = gr_registerForm()
return render(request, 'students/addgrregister.html', {'form': form})
forms.py
from django import forms
from django.forms import ModelChoiceField, ModelForm
from .models import *
class gr_registerForm(ModelForm):
classes_A = forms.ModelChoiceField(queryset=Classes.objects.all())
sections_A = forms.ModelChoiceField(queryset=Sections.objects.all())
classes_C = forms.ModelChoiceField(queryset=Classes.objects.all())
sections_C = forms.ModelChoiceField(queryset=Sections.objects.all())
area_code = forms.ModelChoiceField(queryset=Area.objects.all())
class Meta:
model = gr_register
fields = '__all__'
def init(self, *args, **kwargs):
forms.ModelForm.init(self, *args, **kwargs)
addgrregister.html
{% extends 'authenticate/base.html' %}
{% block content %}
<div class="container">
<h4 class="text-center">ADD GR_REGISTER</h4>
<hr/>
<form method="POST" action="{% url 'addgrregister' %}" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
<div class="form-group row">
<label for="id_{{ field.name }}" class="col-2 col-form-label">{{ field.label }}</label>
<div class="col-10">
{{ field }}
</div>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary" name="button">Add GR_REGISTER</button>
</form>
<br/><br/>
</div>
{% endblock %}
There is nothing returned when form is not valid. I think you try like this:
def addgrregister(request):
form = gr_registerForm(request.POST or None) # it initates a form. If the request type is POST, then there will be a dict available with posted data in request.POST. If request is not POST, then the form will initiate with empty data.
if request.method == 'POST':
if form.is_valid(): # Form valid checks if the submitted form is valid or not. If not, it will store errors in the form. When that form is passed to template, it will show errors in html
form.save() # It will store data in DB
return redirect('home')
# when for is invalid, it will show the error in the form
return render(request, 'students/addgrregister.html', {'form': form})
Update
Show form errors in template:
{% for field in form %}
<div class="form-group row">
<label for="id_{{ field.name }}" class="col-2 col-form-label">{{ field.label }}</label>
<div class="col-10">
{{ field }}
{{ field.errors }} // <-- Updated here
</div>
</div>
{% endfor %}

Django: Form is not valid

I am currently struggling to get my form to work properly. I created the form manually (template.html) and I can see all the data when I call it with print(request.POST) (in views.py - checkout) however form.is_valid(): (in views.py - checkout) doesn't work. Means my form is not valid.
I think the issue is, that I created the form manually and combined it with a model form where I want after validating my data with form.valid() save it in. Can anyone of you guys help me with my problem, why it's not valid?
template.html
<form action="{% url 'checkout:reserve_ticket' %}" method="post">
{% csrf_token %}
{% for ticket in event.tickets.all %}
<p>
{{ ticket.name }} for {{ ticket.price_gross }} with quantity:
<input type="hidden" name="order_reference" value="123456af">
<input type="hidden" name="ticket" value="{{ ticket.id }}">
<input type="hidden" name="ticket_name" value="{{ ticket.name }}">
<input type="number" name="quantity" max="{{ ticket.event.organiser.max_quantity_per_ticket }}" placeholder="0">
</p>
{% endfor %}
<button type="submit" class="btn btn-primary">Continue</button>
</form>
models.py
class ReservedItem(models.Model):
order_reference = models.CharField(
max_length=10,
unique=True
)
ticket = models.ForeignKey(
Ticket,
on_delete=models.PROTECT,
related_name='reserved_tickets'
)
ticket_name = models.CharField(max_length=100)
quantity = models.IntegerField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
forms.py
class ReserveForm(forms.ModelForm):
class Meta:
model = ReservedItem
fields = ['order_reference', 'ticket', 'ticket_name', 'quantity']
views.py - events
# Create your views here.
class EventDetailView(DetailView):
context_object_name = 'event'
def get_object(self):
organiser = self.kwargs.get('organiser')
event = self.kwargs.get('event')
queryset = Event.objects.filter(organiser__slug=organiser)
return get_object_or_404(queryset, slug=event)
views.py - checkout
def reserve_ticket(request):
if request.method == 'POST':
form = ReserveForm(request.POST)
if form.is_valid():
print("Hello World")
return redirect("https://test.com")
else:
print("back to homepage")

MultiValueDictKeyError when I trying to post image

When I trying to add image from admin panel all OK, but when I trying to add image from site, I have this error: image of error. When I trying to post Detail without image, I have the same problem. Before this wasn't.
views.py:
def new_detail(request):
if request.user.is_authenticated:
if request.user.is_superuser:
if request.method == 'POST':
car = request.POST['car']
author = request.user
detail = request.POST['detail']
price = request.POST['price']
description = request.POST['description']
image = request.FILES['images']
detail = Detail(car = car, author = author, detail = detail, price = price, description = description, images = image)
detail.save()
return redirect('/new_detail/')
else:
return redirect('/login/')
return render(request, 'shop/new_detail.html')
new_detail.html:
{% extends 'base.html' %}
{% block content %}
<div class="content container">
<div class="row">
<div class="col-md-8">
<div class=".signin">
<form action="" method="POST">
{% csrf_token %}
<h3>Автомобіль: </h3>
<select name="car">
<option selected>Audi A8 D2 3.3 TDI</option>
<option>Audi A8 D2 3.7</option>
...
...
...
<h3>Ціна: </h3><textarea name="price"></textarea>
<h3>Фотки: </h3><input type="image" name="images" />
<p>
<input type="submit" value="Опублікувати" />
</form>
</div>
</div>
</div>
models.py:
from django.db import models
class Detail(models.Model):
author = models.ForeignKey(
'auth.User',
on_delete=models.CASCADE,)
car = models.CharField(max_length=100)
detail = models.TextField()
description = models.TextField()
price = models.CharField(max_length=30)
images = models.ImageField(upload_to='details', null = True, blank = True)
def __unicode__(self):
return self.detail
def __str__(self):
return self.detail
The first problem is that you are missing enctype="multipart/form-data" from your form tag in the template. See the docs on file uploads for more info.
<form action="" method="POST" enctype="multipart/form-data">
Secondly, your view doesn't handle the case when data is missing from the form. Instead of doing request.POST['detail'] you should be checking if 'detail' in request.POST or using request.POST.get('detail').
However it would be very time consuming to check every field individually. You should look at Django forms and model forms, which can handle a lot of this for you.
from django import forms
class DetailForm(forms.ModelForm):
class Meta:
model = Detail
fields = ['car', 'author', 'detail', 'price', 'description', 'images']
Then your view will be something like
from django.contrib.auth.decorators import user_passes_test
#user_passes_test(lambda u: u.is_superuser)
def new_detail(request):
if request.method == 'POST':
form = DetailForm(request.POST)
if form.is_valid():
detail = form.save()
return redirect('/new_detail/')
else:
form = DetailForm(request.POST)
return render(request, 'shop/new_detail.html', {'form': form})
You can use the form to simplify your template as well:
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
</form>
See the docs on rendering fields manually if you need more control in the template.

Form validation failed in django

I have a simple form
forms.py
class CraveDataForm(forms.ModelForm):
class Meta:
model = crave_data
exclude=['date']
class CraveReplyForm(forms.ModelForm):
class Meta:
model = comments
exclude=['date', 'crave']
model.py
class crave_data(models.Model):
#person = models.ForeignKey(User)
post=models.TextField(blank = True,null = True)
date= models.DateTimeField()
def __unicode__(self):
return self.post
class comments(models.Model):
crave=models.OneToOneField(crave_data)
reply=models.CharField(max_length=1000, blank = True,null = True)
date= models.DateTimeField()
def __unicode__(self):
return self.reply
and views.py
def crave_view(request):
if (request.method=="POST"):
form1=CraveDataForm(request.POST, request.FILES)
if form1.is_valid():
crave_made = form1.save(commit=False)
crave_made.person = request.user
crave_made.save()
messages.success(request, 'You Registered Successfully')
else:
messages.error(request, 'Please enter all required fields')
else:
form1=CraveDataForm()
return render(request, "crave/crave.html", { 'form1' : form1 })
def comment_view(request):
if (request.method=="POST"):
form2 = CraveReplyForm(request.POST, request.FILES)
if form2.is_valid():
reply = form2.save(commit=False)
reply.person=request.user
#reply.crave = request.user
reply.save()
else:
messages.error(request, 'Please enter all required fields')
else:
form2 = CraveReplyForm()
return render(request, "crave/comment.html", { 'form2' : form2 })
my template fie crave.html
<form class="horizontal-form" role="form" action="/crave/" method="post" style="padding: 10px;">
{% csrf_token %}
<div class="form-group" >
<div class="col-sm-10">
{{ form1.post.label_tag }}{{ form1.post }} <br /><br>
</div>
</div>
<input type="submit" class="btn btn-success" value="crave" />
</form>
<form action="/crave/reply_get/">
<input type="submit">
</form>
my comment.html
<form class="horizontal-form" role="form" action="/crave/reply_get/" method="post" style="padding: 10px;">
{% csrf_token %}
<div class="form-group" >
<div class="col-sm-10">
{{ form2.reply.label_tag }} {{ form2.reply }} </br> </br>
</div>
</div>
<input type="submit" class="btn btn-success" value="reply" />
</form>
when i click on crave button i want to save data for form one only without saving data for second form. So comments will be for related posts only. Using foreign key. But i am getting the error here in "reply.crave = crave_made" i want to access the crave made from create_view view.
Help me.
Your forms are derived from UserCreationForm so fields of that form should also be present to make it valid.
But I think you want to inherit from ModelForm and not UserCreationForm.
So change your code as
class CraveDataForm(forms.ModelForm):
class Meta:
model = crave_data
exclude=['date']
class CraveReplyForm(forms.ModelForm):
class Meta:
model = comments
exclude=['date', 'crave']

Categories

Resources