Extending AbstractUser in django - python

I was trying to subclass AbstractUser and stuck in an error on running migrate, and makemigrations says No changes detected
django.db.utils.ProgrammingError: relation "auth_group" does not exist
model:
class SubClient(AbstractUser):
client_id = models.ForeignKey(Client)
phone = models.CharField(max_length=15)
added in settings.py:
AUTH_USER_MODEL = 'myadmin.SubClient'

This error means the auth_group table does not exist in your database. Which means you did not run Django's migration files (python files describing database structure and its changes over time).
As you have your own models, you first need to create migration files for them by running python manage.py makemigrations.
Then run python manage.py migrate to run all migrations (Django's + yours), this will create all database tables (including auth_croup).
Read the doc to lean more about migrations.

when using AbstractUser could i use django's user's builtin password-reset workflow such as password-reset, password-reset-done etc.
the reason i am asking is that i extended user model using AbstractUser but these built-in function not working and i do not get any error but it redirects me to search page and there is no documentation on the internet regarding this issue:
from django.contrib.auth import views as auth_views
path('password-reset/', auth_views.PasswordResetView.as_view(template_name='accounts/password_reset.html'),
name='password-reset'),
path('password-reset/done/',
auth_views.PasswordResetDoneView.as_view(template_name='accounts/password_reset_done.html'),
name='password-reset-done'),
path('password-reset-confirm/<uidb65>/<token>/',
auth_views.PasswordResetConfirmView.as_view(template_name='accounts/password_reset_confirm.html'),
name='password-reset-confirm'),
path('password-reset-complete/s',
auth_views.PasswordResetCompleteView.as_view(template_name='accounts/password_reset_complete.html'),
name='password-reset-complete')

Related

relation "mains_shop" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "mains_shop"

I am Building a Webapp and I am stuck on an Error.
What i am trying to do
I am making a GeoDjango app using Gdal , OSGeo , Postgresql , Postgis. All of them are successfuly installed.
Tutorial :- I am following this Tutorial
When i try to open the Shop panel in Django Admin then it is keep showing me
relation "mains_shop" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM "mains_shop"
And when i delete it and migrate again
then it shows
ValueError: String input unrecognized as WKT EWKT, and HEXEWKB.
But deleting migrations is solving ValueError .
models.py
class Shop(models.Model):
name = models.CharField(max_length=100)
location = models.PointField()
address = models.CharField(max_length=100)
city = models.CharField(max_length=50)
admin.py
#admin.register(Shop)
class ShopAdmin(OSMGeoAdmin):
list_display = ('name', 'location')
settings.py
INSTALLED_APPS = [
'django.contrib.gis',
]
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': '-------',
'USER': '-------',
'PASSWORD': '-------',
'HOST': 'localhost',
'PORT': '',
}
}
What have i tried
First time when error appears then i think that GDal would not installed then I reinstalled it and it successfully installed.
I have reinstalled PostGis .
I have also seen many answers but nothing worked for me.
I have applied migrations many times.
I also tried python manage.py migrate --fake.
I don't know what am i doing wrong.
Any help would be appreciated.
Thank You in Advance.
I know this is not the best solution but it works for me.
This problem occurred to me after I removed my tables in database manually.
my solution:
first of all I removed all of the migration files related to the model which showed in error log. ( you should remove migrations related to Shop model)
change the name of models. (you can change it to Shop2)
run makemigrations and migrate command
change model names back. (change it to Shop again)
make migrations and migrate again
after these steps the problem fixed for me.
also after these step you can delete all new migration files and make migrations again to have only one migration file.
I was facing the same issue for one of the migration file I was generating for model. After spending couple of hours, I came to resolve it by deleting those migration files from django_migrations table.
python manage.py dbshell
select * from django_migrations;
You will see list of all migrations your app wise, delete all those throwing error.
delete from django_migrations where id>=xx
\q
python manage.py migrate

How to display Historical table of django-simple-history in Django admin site?

I have implemented Historical tracking of changes to objects in Django using django-simple-history
https://django-simple-history.readthedocs.io/en/2.10.0/index.html
I have mentioned a field history in Model using which I can query an object's history.
history = HistoricalRecords()
There us also a table created in the database with name appname_historicalmodelname.
I want to display this table appname_historicalmodelname in django admin where in we have list of records sorted by history_time.
As I don't have a Model class for that History table, I'm unable to use admin.site.register(HistoricalModelName). How can I display this table in Django admin site?
Django: 1.11
Python: 2.7
django-simple-history comes with SimpleHistoryAdmin, which bolts on a "History" button to your normal admin view that allows you to see the historical records for a particular model instance. However, if you want to be able to create a django admin view for the historical records themselves, you can do the following (assuming base model CustomModel in app my_app):
from django.apps import apps
from django.contrib import admin
HistoricalCustomModel = apps.get_model("my_app", "HistoricalCustomModel")
#admin.register(HistoricalCustomModel)
class HistoricalCustomModelAdmin(admin.ModelAdmin):
...

How to use one db to run the django service and other to fetch data

i have an existing application data base from which my web site should only fetch the data according to user input. Added database details in the settings.py file and I tried python manage.py integratedb and get the all the 300+ tables came off to my models.py file. I was never able to do python manage.py runserver it threw a million errors. Now i found a work around but i need your opinion on this.
I added the default server into the settings.py and using it i was able to run the server. settings.py looks like this.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase',
},
'user': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME' : 'test',
'USER' : 'testuser',
'PASSWORD': 'readonly',
'HOST' : '10.20.30.40',
'PORT' : '5446',
}
}
Now can i access the user db to fetch data from my form? for example
views.py looks like this
from django.shortcuts import render_to_response
from .models import TestCases
from django.shortcuts import HttpResponse
from django.http import JsonResponse
from django.forms.models import model_to_dict
from django.views.decorators.csrf import csrf_exempt
# Create your views here.
#csrf_exempt
def index(request):
posts = TestCases.objects.all()[:10]
return render_to_response('index.html',{'posts':posts})
where TestCases is a class name from the models.py file.
Now when i click the button to retrieve data i get "no such table: test_cases"
models.py looks like
class TestCases(models.Model):
id = models.BigIntegerField(primary_key=True)
clientid = models.ForeignKey(Clients, db_column='clientid')
projectid = models.ForeignKey(Projects, db_column='projectid')
class Meta:
managed = False
db_table = 'test_cases'
what am i doing wrong to get the data from the user input. please help.
Queryset .using() method
I guess Django is going for the default database.
Try this:
#csrf_exempt
def index(request):
posts = TestCases.objects.using('user').all()[:10]
return render_to_response('index.html',{'posts':posts})
When you set using to your queryset, you can specify which database django is going to query.
More information in Django docs
A better approach, so you don't have to manually set it to all your queries.
You can manually add it to all your queries, or you can create a custom manager to your objects and force it to use a specific database for objects.
Ex:
# this will override the default queryset for objects that use this Manager
class UserDatabaseManager(models.Manager):
def get_queryset(self):
return super().get_queryset().using('user')
class MyModel(models.Models):
objects = UserDatabaseManager()
Then, when you use MyModel, you can query as usually and Django will use the user db for default just for models that have objects = UserDatabaseManager().
Keep in mind that this is just a simple use of the Manager, you can have multiple managers and do a lot of cool stuff.
Take a look at the Django Managers docs
first of all you need to do:
python manage.py inspectdb > models.py
to store your models to models.py
By default, inspectdb creates unmanaged models. That is, managed = False in the model’s Meta class tells Django not to manage each table’s creation, modification, and deletion, if you do want to allow Django to manage the table’s lifecycle, you’ll need to change the managed option above to True (or simply remove it because True is its default value).
Next, run the migrate command to install any extra needed database
python manage.py migrate
integrating docs

OperationalError no such table: categories_article

When i enter django admin interface and click "Articles" i got Error:
OperationalError at /admin/categories/article/
no such table: categories_article
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/categories/article/
Django Version: 1.9
Exception Type: OperationalError
Exception Value:
no such table: categories_article
Exception Location: \Envs\django19\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 323
Python Executable: \Envs\django19\Scripts\python.exe
Python Version: 3.6.3
admin.py
from django.contrib import admin
from .models import Category, Article
admin.site.register(Category)
admin.site.register(Article)
models.py
from django.db import models
class Category(models.Model):
category_name = models.CharField(max_length=200)
class Article(models.Model):
title = models.CharField(max_length=200)
text = models.TextField(max_length=20000)
What should i do to create new "Article" object in django admin?
The problem is with your migrations but it is difficult to say which file is causing the migration error. You have to check each migration file in migrations directory. It basically occurs because you have a migration in which you have already created the table Articles and somehow django skipped that migration, created the new migration file and marked previous migration as successful. Try one of these ways
1) One way of doing this is find the migration file that creates Article table, delete that migration file and change the dependency of the next migration file to the previous migration file or else django will throw an error. And then:
python manage makemigrations
python manage migrate
2) Change the name of Model Article to something else like Articles and then run migration commands:
python manage makemigrations
python manage migrate
3) If none of the above works. This sure will. Delete all migration and rerun all the migrations.

Django 1.5 custom user model plus admin.autodiscover() breaks app

I have a custom user model (it's actually named User as I didn't see any need to name it otherwise) in my Django 1.5c1 project (currently running on the latest from the Django 1.5 branch on github). AUTH_USER_MODEL is defined in my settings properly, so the auth module works correctly and I can log in etc. fine.
However, with the custom user module enabled, the admin site doesn't work. When I add admin.autodiscover() to my urls.py, every page on the site (not just admin pages) throws a NotRegistered exception and says The model User is not registered. The traceback shows that admin.autodiscover() is trying to call admin.site.unregister(User), apparently before it has registered that model.
I tried renaming my user model to something other than User, but it didn't seem to work. I also tried creating my own admin.py for that app, and then I tried manually registering my custom User model with the custom UserAdmin model specified in admin.py before admin.autodiscover() ran, but that actually caused a separate exception saying that User was already registered.
What should I try next in order to get admin.autodiscover() working?
It looks like you need to jump through a few extra hoops if you want your custom User model to work with the admin. From the documentation:
...your User model must define some additional attributes and methods.
These methods allow the admin to control access of the User to admin
content:
class models.CustomUser
is_staff True if the user is allowed to have access to the admin site.
is_active True if the user account is currently active.
has_perm(perm, obj=None) True if the user has the named
permission.
has_module_perms(app_label) True if the user has perm
to access models in the given app.
I set up a brand new empty project with a custom user model and attempted to recreate the situation, which led to a diagnosis: we had added the django-usertools package to the project, which has not been updated for Django 1.5 and apparently conflicts with custom user models. Removing that package from the installed apps list in settings resolved the issue.

Categories