我有一个书面函数def post
,它适用于为帖子添加评论的形式。在这种情况下,当我发送费率表时,不会向数据库添加任何记录。我需要编辑这个函数,这样当我发送一个带有评级帖子的表单时,表单中的所有数据都将保存在数据库中。在数据库中,我需要保存评级的价值,评级用户,日期和评级的帖子。
发送表单后我只需要为数据库添加值。
views.py :
class IndexView(AllAdsViewMixin, ListView):
model = UserContent
template_name = 'user_content/list.html'
context_object_name = 'object'
def get_queryset(self):
"""Return the last all five published contents"""
return UserContent.objects.filter(state='1').order_by('-published')[:5]
def get_context_data(self, **kwargs):
comment_initial_data = {
'content_type': ContentType.objects.get_for_model(self.model).id
}
reply_initial_data = {
'content_type': ContentType.objects.get_for_model(Comment).id
}
comment_form = CommentForm(initial=comment_initial_data)
reply_form = CommentForm(initial=reply_initial_data)
mainpage_images = MainPageImages.objects.first()
rate_form = RateForm()
context = super(IndexView, self).get_context_data(**kwargs)
context['comment_form'] = comment_form
context['reply_form'] = reply_form
context['mainpage_images'] = mainpage_images
context['rate_form'] = rate_form
return context
def post(self, request, **kwargs):
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
content_type_id = comment_form.cleaned_data.get('content_type')
object_id_data = comment_form.cleaned_data.get('object_id')
content_data = comment_form.cleaned_data.get('content')
content_type = ContentType.objects.get_for_id(content_type_id)
print(object_id_data)
print(content_data)
new_comment, created = Comment.objects.get_or_create(
user=request.user,
content_type=content_type,
object_id=object_id_data,
content=content_data,
)
else:
print(comment_form.errors)
return self.get(request, **kwargs)
forms.py :
from django import forms
from .models import Rate
class RateForm(forms.ModelForm):
class Meta:
model = Rate
fields = (
'rate_value',
)
models.py :
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from user_content.models import UserContent
class Rate(models.Model):
user_content = models.ForeignKey(UserContent,
related_name='rates',
verbose_name=_('User Content')
)
rate_value = models.DecimalField(decimal_places=2, max_digits=3,
verbose_name=_('rates'))
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
verbose_name=_('User')
)
created = models.DateTimeField(_('Date Created'), auto_now_add=True)