Сбой ограничения NOT NULL: ial_profile.user_id
Я новичок в Django и пытался следовать учебнику. Но я столкнулся с этой проблемой и не могу решить ее самостоятельно. Когда я пытаюсь получить доступ к 127.0.0.1:8000/profile/id(1,2,3...), он выдает 'IntegrityError'. Может ли кто-нибудь помочь мне решить эту проблему?
Пример кода :
views.py
from django.shortcuts import render
from .models import Profile
# Create your views here.
def dashboard(request):
return render(request, "base.html")
def profile_list(request):
profiles = Profile.objects.exclude(user=request.user.id)
return render(request, "ial/profile_list.html", {"profiles": profiles})
def profile(request, pk):
if not hasattr(request.user, 'profile'):
missing_profile = Profile(user=request.user.id)
missing_profile.save()
profile = Profile.objects.get(pk=pk)
# edit 1
if request.method == "POST":
current_user_profile = request.user.profile
data = request.POST
action = data.get("follow")
if action == "follow":
current_user_profile.follows.add(profile)
elif action == "unfollow":
current_user_profile.follows.remove(profile)
current_user_profile.save()
return render(request, 'ial/profile.html', {'profile': profile})
models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
follows = models.ManyToManyField(
"self",
related_name = "followed_by",
symmetrical=False,
blank=True
)
def __str__(self):
return self.user.username
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
user_profile = Profile(user=instance)
user_profile.save()
user_profile.follows.set([instance.profile.id])
user_profile.save()
profile.html
{% extends 'base.html' %}
{% block content %}
<div class="column">
<div class="block">
<h1 class="title is-1">
{{profile.user.username|upper}}'s djail
</h1>
</div>
<form method="post">
{% csrf_token %}
<div class="buttons has-addons">
{% if profile in user.profile.follows.all %}
<button class="button is-success is-static">Follow</button>
<button class="button is-danger" name="follow" value="unfollow">
Unfollow
</button>
{% else %}
<button class="button is-success"name="follow" value="follow">Follow</button>
<button class="button is-danger is-static">Unfollow</button>
{% endif %}
</div>
</div>
<div class="column is-one-third">
<div class="block">
<a href="{% url 'ial:profile_list' %}">
<button class="button is-dark is-outlined is-fullwidth">
All Profiles
</button>
</a>
</div>
<div class="block">
<h3 class="title is-4">
{{profile.user.username}} follows:
</h3>
<div class="content">
<ul>
{% for following in profile.follows.all %}
<li>
<a href="{% url 'ial:profile' following.id %}">
{{ following }}
</a>
</li>
{% endfor %}
</ul>
</div>
</div>
<div class="block">
<h3 class="title is-4">
{{profile.user.username}} is followed by:
</h3>
<div class="content">
<ul>
{% for follower in profile.followed_by.all %}
<li>
<a href="{% url 'ial:profile' follower.id %}">
{{ follower }}
</a>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
{% endblock content %}
Терминальный выход
Слежение за изменениями файлов с помощью StatReloader Выполнение проверки системы...
Проверка системы не выявила проблем (0 промолчало). Ноябрь 26, 2022 - 09:16:18 Django версии 4.1.3, использование настроек 'social.settings' Запуск сервера разработки по адресу http://127.0.0.1:8000/. Выйдите из сервера с помощью CONTROL-C. Внутренняя ошибка сервера: /profile/1 Traceback (последний последний вызов): File "/home/kali/.local/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) Файл "/home/kali/.local/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", строка 357, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: ial_profile.user_id
Вышеуказанное исключение стало непосредственной причиной следующего исключения:
Traceback (most recent call last): File "/home/kali/.local/lib/python3.10/site-packages/django/core/handlers/exception.py",
строка 55, в inner response = get_response(request) Файл "/home/kali/.local/lib/python3.10/site-packages/django/core/handlers/base.py", строка 197, в _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Файл "/home/kali/djial/social/ial/views.py", строка 17, в profile missing_profile.save() Файл "/home/kali/.local/lib/python3.10/site-packages/django/db/models/base.py", строка 812, в save self.save_base( Файл "/home/kali/.local/lib/python3.10/site-packages/django/db/models/base.py", строка 863, в save_base обновлено = self._save_table( Файл "/home/kali/.local/lib/python3.10/site-packages/django/db/models/base.py", строка 1006, in _save_table results = self._do_insert( Файл "/home/kali/.local/lib/python3.10/site-packages/django/db/models/base.py", строка 1047, в _do_insert return manager._insert( Файл "/home/kali/.local/lib/python3.10/site-packages/django/db/models/manager.py", строка 85, в manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) Файл "/home/kali/.local/lib/python3.10/site-packages/django/db/models/query.py", строка 1790, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) Файл "/home/kali/.local/lib/python3.10/site-packages/django/db/models/sql/compiler.py", строка 1660, в execute_sql cursor.execute(sql, params) Файл "/home/kali/.local/lib/python3.10/site-packages/django/db/backends/utils.py", строка 103, в execute return super().execute(sql, params) Файл "/home/kali/.local/lib/python3.10/site-packages/django/db/backends/utils.py", строка 67, в execute return self._execute_with_wrappers( Файл "/home/kali/.local/lib/python3.10/site-packages/django/db/backends/utils.py", строка 80, в _execute_with_wrappers return executor(sql, params, many, context) Файл "/home/kali/.local/lib/python3.10/site-packages/django/db/backends/utils.py", строка 84, in _execute with self.db.wrap_database_errors: Файл "/home/kali/.local/lib/python3.10/site-packages/django/db/utils.py", строка 91, in exit raise dj_exc_value.with_traceback(traceback) from exc_value Файл "/home/kali/.local/lib/python3.10/site-packages/django/db/backends/utils.py", строка 89, in _execute return self.cursor.execute(sql, params) Файл "/home/kali/.local/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", строка 357, в execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: ial_profile.user_id [26/Nov/2022 09:16:29] "GET /profile/1 HTTP/1.1" 500 140002
.
Я знаю, что проблема, возможно, связана с missing_profile.save() и мне нужно использовать .save(commit=False), но не знаю, как это сделать...
Заранее спасибо.
Пытался получить доступ к 127.0.0.1:8000/profile/id(1,2,3...), но получил ошибку IntegrityError.