'Null value in column violates not-null constraint after deleting objects incorrectly

Help me please I don't know what's going on. I wrote some simple blog, where I could add posts and comments. It was working well.

views.py:

def add_comment_to_post(request, pk):
    post = get_object_or_404(Post, pk=pk) # calls the given model and get the object, type = <class 'blog.models.Post'
    if request.method == "POST": # if we posted data
        form = CommentForm(request.POST) 
        if form.is_valid(): # if all fields are filled
            comment = form.save(commit=False) # create instance and return which not saved in database "Comment" <class Comment>
            comment.post = post # return Title
            comment.author = request.user
            comment.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = CommentForm() # type = <class 'blog.forms.CommentForm'>
    return render(request, 'blog/add_comment_to_post.html', {'form': form})

But when I added a function for deleting comments, that wrote me a mistake, like this:

null value in column "approved_comment" of relation "blog_comment" violates not-null constraint

views.py:

def comment_remove(request, pk):
       post = get_object_or_404(Post, pk=pk)
       comment = get_object_or_404(Comment, pk=pk)
       print(comment)
       comment.delete()
       return redirect('post_detail', pk=post.pk)

I think I deleted comment incorrectly. I don't understand how primary keys works, how comments and posts are related each other. And I don't understand how to understand it.

ps. models.py:

class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, 
related_name="author_name",
on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

def publish(self):
    self.published_date = timezone.now()
    self.save()

def __str__(self):
    return self.title

def approved_comments(self):
    return self.comments.filter(approved_comment=True)

class Meta:
    ordering = ['-published_date']

class Comment(models.Model):
    post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, 
related_name='comments')
    author = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    approved_comment = models.BooleanField(default=False),
    # parent = models.ForeignKey('self', null=True, blank=True, 
related_name='replies')

def approve(self):
    self.approved_comment = True
    self.save()

def __str__(self):
    return 'Comment {} by {}'.format(self.text, self.author)

pps. forms.py:

from xml.etree.ElementTree import Comment
from django import forms
from .models import Post, Comment

class PostForm(forms.ModelForm):

    class Meta:
        model = Post
        fields = ('title', 'text',)

class CommentForm(forms.ModelForm):

    class Meta:
        model = Comment
        fields = ('text',)


Solution 1:[1]

To understand how to delete comments we need to understand how pk(primary keys) and related_name works.

Let's see model class Comment. Pay attention for post and related_name='comments' and than see it in post_detail.html.

class Comment(models.Model):
    post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, 
related_name='comments')
    author = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    approved_comment = models.BooleanField(default=False)

post_detail.html:

<a class="btn btn-default" href="{% url 'add_comment_to_post' pk=post.pk %}">Add comment</a>
    {% for comment in post.comments.all %}
        <div class="comment">
            <a class="btn btn-default" href="{% url 'comment_remove' pk=comment.pk %}"><span class="glyphicon glyphicon-remove"></span></a>
            <div class="date">{{ comment.created_date }}</div>
            <strong>{{ comment.author }}</strong>
            <p>{{ comment.text|linebreaks }}</p>
        </div>
    {% empty %}
        <p>No comments here yet :(</p>
    {% endfor %}

post.comments.all - post is relating for model our Post model. The related_name specifies the name of the relation in reverse, so in this case accessing the Comment of a given Post object. [https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name] Now you know how we get comment.pk.

After that please pay attention how we're removing comment. views.py:

def comment_remove(request, pk):
    comment = get_object_or_404(Comment, pk=pk)
    comment.delete()
    return redirect('post_detail', pk=comment.post.pk)

Look at the comment.post.pk. In our Comment model we have key post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments'), which is relating with our Post Model. That's it!

Solution 2:[2]

It's better to send your code here. But below ways may help you.

How to Pass Data Between a Parent Component and a Child Component Firstly, let's pass data between a parent component and a child component.

First, you'll need to create two components, one parent and one child.

    import React from 'react'

    export default function Parent() {
    return (
    <div>
      
    </div>
  )
}

Parent.js

 import React from 'react'

     export default function Child() {
    return (
        <div>
            
        </div>
     )
    }

Next, you'll import the child component in the parent component and return it.

    import React from 'react'
    import Child from './Child';

    export default function Parent() {
    return (
    <div>
      <Child/>
    </div>
   )
   }

Then you'll create a function and a button to trigger that function. Also, you'll create a state using the useState Hook to manage the data.

import React from 'react'
import Child from './Child';
import { Button } from 'semantic-ui-react';
import { useState } from 'react';
import './App.css';

export default function Parent() {
  const [data, setData] = useState('');
  
  const parentToChild = () => {
    setData("This is data from Parent Component to the Child Component.");
  }
  return (
    <div className="App">
      <Child/>
      
      <div>
        <Button primary onClick={() => parentToChild()}>Click Parent</Button>
      </div>
    </div>
  )
}

read more

Solution 3:[3]

You could just read it from another component using AsyncStorage. There is no need for passing here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sergo
Solution 2 Vahid Afshari
Solution 3 Tadej Slemenšek