1

I wanted to create comments in my web application. Each comment should connect to only one post. I can add the comments via the admin field but when I try it on the webpage I am getting errors. Can You help me please. Thank you very much

models.py

from django.db import models
from django.contrib.auth.models import User
from django.utils.text import slugify
# Create your models here.

class PostModel(models.Model):
    post = models.TextField(max_length=256, unique=True)
    slug = models.SlugField(max_length=20, unique=True)
    author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='post_author')
    created_on = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_on']

    def save(self, *args, **kwargs):
        self.slug = self.slug or slugify(self.post)
        super().save(*args, **kwargs)


    def __repr__(self):
        return f"{self.post}"


class CommentModel(models.Model):
    post = models.ForeignKey('dictionary.PostModel', on_delete=models.CASCADE, related_name='post_comment')
    comment=models.TextField(max_length=256,unique=True)
    author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='comment_author')
    created_on = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_on']


    def get_absolute_url(self):
        return reverse("comment_detail",kwargs={'pk':self.pk})


    def __str__(self):
        return self.comment

views.py

from django.shortcuts import render,redirect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import generic
from django.views.generic.edit import FormMixin
from .models import PostModel,CommentModel
from .forms import PostForm,CommentForm
from django.urls import reverse
from django.views.generic.edit import ModelFormMixin




# Create your views here.
class PostList(LoginRequiredMixin,generic.CreateView):
    template_name = 'home.html'
    form=PostForm
    model = PostModel
    fields=['post']
    success_url="/home"

    def form_valid(self, form):
        form.instance.author=self.request.user
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context ['postmodel_list'] = PostModel.objects.order_by('-created_on')
        return context




class PostDetail(LoginRequiredMixin,ModelFormMixin,generic.DetailView):
    model = PostModel
    template_name = 'post_detail.html'
    form_class=CommentForm


    def get_success_url(self):
        return reverse('post_detail',kwargs={'slug':self.object.slug})

    def get_context_data(self, **kwargs):
        context = super(PostDetail,self).get_context_data(**kwargs)
        context ['commentmodel_list'] = CommentModel.objects.filter(post=self.object).order_by('-created_on')
        return context

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        form = self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)


    def form_valid(self, form):
        form.instance.author = self.request.user
        form.instance.post = self.object
        return super(PostDetail,self).form_valid(form)

traceback

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/home/bu-da-benim-ilk-postum/

Django Version: 3.0.8
Python Version: 3.8.1
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'crispy_forms',
 'account',
 'dictionary']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Users\ekrem\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\ekrem\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\ekrem\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\ekrem\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\ekrem\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch
    return super().dispatch(request, *args, **kwargs)
  File "C:\Users\ekrem\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Users\ekrem\Documents\Django\project\beehive\dictionary\views.py", line 51, in post
    return self.form_valid(form)
  File "C:\Users\ekrem\Documents\Django\project\beehive\dictionary\views.py", line 59, in form_valid
    return super(PostDetail,self).form_valid(form)
  File "C:\Users\ekrem\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\edit.py", line 125, in form_valid
    self.object = form.save()
  File "C:\Users\ekrem\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\forms\models.py", line 459, in save
    self.instance.save()
  File "C:\Users\ekrem\Documents\Django\project\beehive\dictionary\models.py", line 17, in save
    super().save(*args, **kwargs)
  File "C:\Users\ekrem\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 745, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\ekrem\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 782, in save_base
    updated = self._save_table(
  File "C:\Users\ekrem\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 864, in _save_table
    updated = self._do_update(base_qs, using, pk_val, values, update_fields,
  File "C:\Users\ekrem\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 917, in _do_update
    return filtered._update(values) > 0
  File "C:\Users\ekrem\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 771, in _update
    return query.get_compiler(self.db).execute_sql(CURSOR)
  File "C:\Users\ekrem\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py", line 1500, in execute_sql
    cursor = super().execute_sql(result_type)
  File "C:\Users\ekrem\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py", line 1139, in execute_sql
    sql, params = self.as_sql()
  File "C:\Users\ekrem\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py", line 1460, in as_sql
    raise TypeError(

Exception Type: TypeError at /home/bu-da-benim-ilk-postum/
Exception Value: Tried to update field dictionary.PostModel.post with a model instance, PostModel object (4). Use a value compatible with TextField.

I also had a str method where I returned self.comment or str(self.comment) or had a repr function but I get everytime strange errors.

3
  • Please edit your question and add the CommentForm and PostModel codes as well. Commented Jul 25, 2020 at 13:28
  • sorry to bother you. But could you please add the error stacktrace as well? Commented Jul 25, 2020 at 13:59
  • no problem, here you are Commented Jul 25, 2020 at 14:06

1 Answer 1

1

The __str__ method implementations are not correct. I think you should use the __repr__ method instead. But if you're sure you want to use the __str__ method please don't use the str function inside.

I suggest something like this:

def __repr__(self):
    return f"{self.post}"
Sign up to request clarification or add additional context in comments.

7 Comments

now I am gettng this error: Tried to update field dictionary.PostModel.post with a model instance, <PostModel PostModel object (4)>. Use a value compatible with TextField.
Updated the answer. please retry.
That's odd! could you please send me the new stacktrace? and just to be sure, does your code now has only __repr__ methods and no __str__ ones? did you change CommentModel's method to use self.comment?
I took my new code in the question, I am only using repr, and the I did no understand the second question
oh! you had two __str__ methods. one in PostModel and the other in CommentModel. they should return respectively f"{self.post}" and f{self.comment}". and the second line of form_valid method of PostDetail is causing the new error. self.instance.post should be assigned a text, not an object.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.