I want to create a comment system. I can take username
, doc_id
, and comp_name
, but I cannot get the comment_others
. I think there is a problem saving the form. How can I fix it?
views.py
JavaScript
x
22
22
1
def ocr(request, id):
2
pdf = get_object_or_404(Pdf, id=id)
3
approval = ApprovalProcess(user_id=request.user, highest_rank=1)
4
current_user = request.user
5
userP = UserProfile.objects.get_or_create(username=current_user)
6
7
if request.method == 'POST':
8
form_2 = CommentForm(request.POST or None, instance=pdf)
9
10
if form_2.is_valid():
11
form_2.instance.username=request.user
12
form_2.instance.comp_name = userP[0].company
13
form_2.instance.doc_id = pdf
14
form_2.save()
15
16
else:
17
form_2 = CommentForm()
18
19
comment_obj = CommentFromOthers.objects.filter(doc_id=pdf).order_by("-created_date")
20
21
..
22
models.py
JavaScript
1
7
1
class CommentFromOthers(models.Model):
2
comp_name = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True)
3
doc_id = models.ForeignKey(Pdf, on_delete=models.DO_NOTHING, null=True)
4
comment_others = RichTextField(blank=True)
5
created_date = models.DateTimeField(default=datetime.now())
6
username = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
7
forms.py
JavaScript
1
7
1
class CommentForm(forms.ModelForm):
2
comments = RichTextField
3
4
class Meta:
5
model = CommentFromOthers
6
fields = ('comment_others',)
7
template.html
JavaScript
1
14
14
1
<div class="card">
2
<div class="card-header">
3
<div class="card-title">Risk Rating & Credit Limit</div>
4
</div>
5
<div class="card-body">
6
{% for comment in comment_obj %}
7
<li>
8
<h5>{{ comment.username }} - {{ comment.created_date }}</h5>
9
<h4>{{ comment.comment_others|safe}}</h4>
10
</li>
11
{% endfor %}
12
</div>
13
</div>
14
And there are two forms on the same page. When I save this form, the other form disappears. Why it could be happening?
JavaScript
1
11
11
1
if request.method == 'POST':
2
form = PdfRiskForm(request.POST, request.FILES, instance=pdf)
3
4
if form.is_valid():
5
form.save()
6
7
approval.save()
8
9
else:
10
form = PdfRiskForm()
11
Note: RichTextField
is the text field of django-ckeditor. But the problem is not relevant to that because when I change it as charfield it still doesn’t save the comment_others
field.
Advertisement
Answer
forms.py
JavaScript
1
2
1
comments = forms.CharField(widget=forms.Textarea)
2
views.py
JavaScript
1
7
1
if request.method == 'POST':
2
form_2 = CommentForm(request.POST or None, instance=id) #or user.id
3
4
if form_2.is_valid():
5
6
form_2.save()
7
by eliminating those lines in views.py will automatically save the fields in your database.