Django: no such table: users_profile - python

Django noob here. Whenever I extend the base User Model, and try to access or edit the new fields, I receive the following error [... table not found].
OperationalError at /admin/users/profile/
no such table: users_profile
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/users/profile/
Django Version: 3.1.2
Exception Type: OperationalError
Exception Value:
no such table: users_profile
Exception Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py, line 413, in execute
Python Executable: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3
Python Version: 3.7.7
Python Path:
['/Users/rexmarkman/Desktop/ComputerScienceIA/newproject',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload',
'/Users/rexmarkman/Library/Python/3.7/lib/python/site-packages',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages']
Server time: Sun, 30 May 2021 12:52:22 +0000
Im not sure why this is happening as I have ran makemigrations and migrate multiple times. For reference here are my migrations
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Profile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('profile_picture', models.ImageField(default='default.jpg', upload_to='profile_pictures')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
Also here is my models.py for further reference
from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField(default = 'default.jpg', upload_to = 'profile_pictures')
def __str__(self):
return f'{self.user.username} Profile'
Also worth noting that this issue occurs when attempting to change the profile table in the admin site
Please let me know if you need to know anything else.
Thanks for any help :)

Try to delete the migrations folder from your app and db.sqilte3 file and then retry -:
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
and then retry your error must be solved

Related

How can I handle the "Django - Database error: no such table" error?

I'm pretty new to django and I'm stuck at the problem with models. Here is my users app's models file:
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator, MaxValueValidator
from django.urls import reverse
from PIL import Image
class Schedule(models.Model):
title = models.CharField(max_length=150)
context = models.TextField()
class Input(models.Model):
DAYS_OF_FITNESS = [
('month', '30'),
('month_2', '60'),
('month_3', '90'),
]
weight = models.PositiveIntegerField(validators=[MinValueValidator(40)])
age = models.PositiveIntegerField(validators=[MinValueValidator(12)])
days = models.CharField(
max_length=20, choices=DAYS_OF_FITNESS, default='30')
athlete = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)
schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
I'm trying to link each user with its input using OneToOneField and Schedule is linked as a foreign key to Input model
But when I'm trying to migrate models, I'm getting this error:
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: users_input
I checked that Both models are in django settings, and I migrated them. BTW, I'm using signals to save inputs automatically, (just for note if it helps)
It's because that table doesn't exist in the database. To create tables you have to do the following. Execute the following commands in your terminal.
python manage.py makemigrations
python manage.py migrate

Django Postgres ArrayField makemigrations

I'm looking to use the PostgreSQL-specific ArrayField in my Django project, but it doesn't show up in the migrations after I run makemigrations. Any ideas why?
Django v2.1
Postgresql v9.6.6
# Models.py
from django.db import models
from django.contrib.postgres.fields import ArrayField
class MyClassName(models.Model):
udi = ArrayField(models.CharField()),
version = models.IntegerField()
Then I run: python3 manage.py makemigrations
# 0001_initial.py
migrations.CreateModel(
name='MyClassName',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('version', models.IntegerField()),
],
),
As you can see, the field 'udi' is suspiciously missing.
The problems are a comma at the end of the ArrayField() and CharField would need max_length too.
class MyClassName(models.Model):
udi = ArrayField(models.CharField(max_length=10))
version = models.IntegerField()
Run makemigrations again and you will get a migration you want.

IntegrityError: NOT NULL constraint failed with default=None, blank=True null=True in model?

I am running my script in the django shell, and the error is coming from these lines:
new_species = Species(genus=new_genus, species=row[4])
new_species.save()
This error:
IntegrityError: NOT NULL constraint failed:
birds_species.species_english
I am trying to save information to this model:
class Species(models.Model):
genus = models.ForeignKey(Genus, default=None)
species = models.CharField(max_length=100, default=None)
species_english = models.CharField(max_length=100, default=None, blank=True, null=True)
def __str__(self):
return self.species
I confirm that that migrations are up-to-date because I run the following lines in my django project:
$ python manage.py makemigrations birds
No changes detected in app 'birds'
$ python manage.py migrate
Operations to perform:
Apply all migrations: sessions, admin, polls, auth, contenttypes, birds
Running migrations:
No migrations to apply.
The problem is I am trying to save an object to the Species model, without defining the 1 column species_english. From the model it can be seen that I have default=None, blank=True, null=True which is what I thought we needed to allow null values by default. What do I have wrong here?
I am using the default sqlite3 DB for the DB backend.
Thanks!
EDIT
Here is the migration file contents:
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-06-17 14:02
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('birds', '0007_speciesfile'),
]
operations = [
migrations.AddField(
model_name='species',
name='species_english',
field=models.CharField(blank=True, default=None, max_length=100, null=True),
),
]

Django User object error in models.py

I am writing my first Django project and using Django 1.7, and for my login and authentication I am using the Django User model. I am now creating my models. Project and User share a Many-to-Many relationship
models.py:
from django.db import models
from django import forms
from django.contrib.auth.models import User
class Project(models.Model):
project_name = models.CharField(max_length=128, unique = True)
project_description = models.CharField(max_length=128)
users_annotating = models.ManyToManyField(User)
However, I get this error when I try to migrate:
ValueError: Related model 'auth.User' cannot be resolved
Does anyone understand this problem?
I'm guessing that you have
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
in your newly created Django 1.7 migration.
If you comment out that dependency and just in case replace it with
dependencies = [
('auth', '__first__'),
]
things should work.

django-rest-framework tutorial 4 (authentic​ation-and-​permission​s) issue

After finishing tutorial 1-3 smoothly, I followed the tutorial (http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html) and finished sections up to "Adding endpoints for our User models".
(In other words, adding "url(r'^users/$', views.UserList.as_view()),
url(r'^users/(?P[0-9]+)/$', views.UserInstance.as_view())," was done.)
Then, I ran the server with the command of "python manage.py runserver" and point my browser to http://127.0.0.1:8000/users/ and got the following error message:
(message starts)
NameError at /users/
name 'User' is not defined
Request Method: GET
Request URL: http://127.0.0.1:8000/users/
Django Version: 1.4.3
Exception Type: NameError
Exception Value: name 'User' is not defined
Exception Location: /home/user/tutorial/snippets/serializers.py in Meta, line 14
(message ends)
Did I miss something?
The code in my serializer.py was:
from django.forms import widgets
from rest_framework import serializers
from snippets import models
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = models.Snippet
fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
class UserSerializer(serializers.ModelSerializer):
snippets = serializers.ManyPrimaryKeyRelatedField()
class Meta:
model = User
fields = ('id', 'username', 'snippets')
You'll need to import Django's user class.
from django.contrib.auth.models import User
That import line isn't currently mentioned. I guess it probably should be.

Categories

Resources