Trying to set up autocomplete_fields in django.
I have following model:
from django.db import models
class Genre(models.Model):
title = models.CharField(max_length=255)
class Movie(models.Model):
title = models.CharField(max_length=255)
year = models.IntegerField()
time = models.CharField(max_length=255)
director = models.CharField(max_length=255)
genre = models.ManyToManyField(Genre)
image = models.ImageField(upload_to='images/')
actors = models.TextField()
summary = models.TextField()
admin.py:
from django.contrib import admin
from .models import Movie, Genre
class SettingAdmin(admin.ModelAdmin):
search_fields = ['genre']
class MovieAdmin(admin.ModelAdmin):
autocomplete_fields = ['genre']
admin.site.register(Movie, MovieAdmin)
admin.site.register(Genre)
Error Message:
Exception in thread django-main-thread:
Traceback (most recent call last):
File "c:\users\ali\appdata\local\programs\python\python38\lib\threading.py", line 932, in _
bootstrap_inner
self.run()
File "c:\users\ali\appdata\local\programs\python\python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Ali\Desktop\cinemaEnv\lib\site-packages\django\utils\autoreload.py", line 53, in
wrapper
fn(*args, **kwargs)
File "C:\Users\Ali\Desktop\cinemaEnv\lib\site-packages\django\core\management\commands\runserver.py",
line 117, in inner_run
self.check(display_num_errors=True)
File "C:\Users\Ali\Desktop\cinemaEnv\lib\site-packages\django\core\management\base.py", line 441, in
check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
<class 'movies.admin.MovieAdmin'>: (admin.E040) ModelAdmin must define "search_fields", because it's
referenced by MovieAdmin.autocomplete_fields.
i try this code with User model from django.contrib.auth.models and it worked.
i try this code with User model from django.contrib.auth.models and it worked.
As error msg said:
you need to define "search_fields" in Genre admin, since you use autocomplete_fields = ['genre'],
and don't forget to register Genre model with it.
class GenreAdmin(admin.ModelAdmin):
search_fields = ['title']
admin.site.register(Genre, GenreAdmin)
Related
I had a model Profile which was an extension to my User model which was the ForeignKey of my Post model, but I changed it to an AbstractUser and now if I try migrating or running and refreshing the page the server I get an error.
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
bio = models.TextField(max_length=500,null=True)
from django.db import models
from django.conf import settings
from django.urls import reverse
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
title = models.CharField(max_length=100)
content = models.TextField()
def get_absolute_url(self):
return reverse('post-details', kwargs={'pk': self.pk})
settings.py
INSTALLED_APPS = [
...
'posts',
'users',
]
AUTH_USER_MODEL = 'users.User'
error message after I try migrating
Apply all migrations: admin, auth, contenttypes, posts, sessions, users
Traceback (most recent call last):
File "/home/user/Projects/DNF/Project/manage.py", line 22, in <module>
main()
File "/home/user/Projects/DNF/Project/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.10/dist-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/base.py", line 402, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/base.py", line 448, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/base.py", line 96, in wrapped
res = handle_func(*args, **kwargs)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/commands/migrate.py", line 295, in handle
pre_migrate_apps = pre_migrate_state.apps
File "/usr/local/lib/python3.10/dist-packages/django/utils/functional.py", line 57, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.10/dist-packages/django/db/migrations/state.py", line 566, in apps
return StateApps(self.real_apps, self.models)
File "/usr/local/lib/python3.10/dist-packages/django/db/migrations/state.py", line 637, in __init__
raise ValueError("\n".join(error.msg for error in errors))
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'.
The field posts.Post.author was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'.
The field users.Profile.user was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'.
I easily solved it by deleting all the migration files in the migrations folder except the init.py file. And also delete db.sqlite3. Now run the following commands : python manage.py makemigrations and then python manage.py migrate. Now you'll have to create the super user once again, so for this just type the following commmand : python manage.py createsuperuser. Then it will prompt for username, email and password, so enter your credentials and all will continue to work properly once again I hope that this will be helpful.
try to directly reference the User model, not through settings
change the foreign key field to this:
author = models.ForeignKey("users.User", on_delete=models.CASCADE, null=True)
To have a reference to the User model, you should not do through settings directly instead you can use get_user_model() function. This function will return the currently active User model of project( the custom User model if one is specified, or User otherwise).
So change the foreign key field of your Post model like below:
from django.db import models
from django.conf import settings
from django.urls import reverse
from django.contrib.auth import get_user_model
User = get_user_model()
class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
...
Reference: get_user_model() [Django-doc]
I have made a new model postComments for my blogging website and now I am facing the above issue:
models.py:
from django.db import models
from django.contrib.auth.models import User
from django.utils.timezone import now
# Create your models here.
class post(models.Model):
SrNo = models.AutoField(primary_key=True)
title = models.CharField(max_length=50)
content = models.TextField()
author = models.CharField(max_length=50)
slug = models.SlugField(max_length=200)
timeStamp = models.DateTimeField(blank=True)
def __str__(self):
return self.title + " by " + self.author
class postComments(models.Model):
sno = models.AutoField(primary_key=True)
comment = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(post, on_delete=models.CASCADE)
parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True)
timestamp = models.DateTimeField(default=now)
after writing the above '''postComments``` model the log window is showing me this error:
error log
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run
self.check(display_num_errors=True)
File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\core\management\base.py", line 392, in check
all_issues = checks.run_checks(
File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\contrib\admin\checks.py", line 54, in check_admin_app
errors.extend(site.check(app_configs))
File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\contrib\admin\sites.py", line 84, in check
if modeladmin.model._meta.app_config in app_configs:
AttributeError: 'postComments' object has no attribute 'model'
admin.py:
from django.contrib import admin
from blog.models import post, postComments
# Register your models here.
admin.site.register((post), (postComments))
urls.py(blog app):
from django.urls import path, include
from blog import views
urlpatterns = [
path('', views.blogHome, name='home'),
path('<str:slug>', views.blogPost, name='blogpost'),
# here blog_name is string variable which will take the input after /blog/anyblogname
# and after this the page will display: this is 'anyblogname'
]
before adding this new model, the website was working just fine.
The correct way to register models is one per register call
from django.contrib import admin
from blog.models import post, postComments
# Register your models here.
admin.site.register(post)
admin.site.register(postComments)
I have some troubles with migrating my database in django
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "E:\Env\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "E:\Env\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "E:\Env\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "E:\Env\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 350, in execute
self.check()
File "E:\Env\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 379, in check
include_deployment_checks=include_deployment_checks,
File "E:\Env\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 366, in _run_checks
return checks.run_checks(**kwargs)
File "E:\Env\Python\Python37-32\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks
new_errors = check(app_configs=app_configs)
File "E:\Env\Python\Python37-32\lib\site-packages\django\contrib\auth\checks.py", line 74, in check_user_model
if isinstance(cls().is_anonymous, MethodType):
File "E:\Env\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 470, in __init__
_setattr(self, field.attname, val)
File "E:\Env\Python\Python37-32\lib\site-packages\django\db\models\fields\related_descriptors.py", line 537, in __set__
% self._get_set_deprecation_msg_params(),
TypeError: Direct assignment to the reverse side of a related set is prohibited. Use username.set() instead.
Here is my models.py:
class PostComments(models.Model):
post = models.ForeignKey(InfoPost, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="username")
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
#approved_comment = models.BooleanField(default=False)
reply_to = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE, related_name='replies')
#def __str__(self): return 'Comment by {} on {}'.format(self.name, self.post)
I am trying to make comments system for post in my website, but there is some error occured. I don't know whats wrong with my model, but if i try to make migrations without my new PostComments model, its migrating pretty fine.
UPD. Here is my code, where i am using my PostComments model
forms.py
class CommentsForm(forms.ModelForm):
post = forms.CharField(required=False)
author = forms.CharField(required=False)
class Meta:
model = PostComments
fields = '__all__'
views.py
def post(request, slug):
post = get_object_or_404(InfoPost, slug=slug)
comment_list = CommentsForm._meta.model.objects.all()
if request.user.is_authenticated:
user = User.objects.get(username=request.user.username)
if request.method == 'POST':
comment = CommentsForm(request.POST)
print(comment.is_valid())
if comment.is_valid():
com = comment.save(commit=False)
com.author = request.user
com.post = post
com.save()
return redirect('post', slug=slug)
else:
comment_form = CommentsForm()
return render_to_response('MainPage/Post.html',
{'post': post, "user": user, 'img_w': image_w, 'img_h': image_h,
'comments_list': comment_list, 'comment_form': comment_form})
return render_to_response('MainPage/Post.html', {'post': post, 'img_w': image_w, 'img_h': image_h, 'comments_list': comment_list})
I was thinking, its started after i tried to get all objects of comments for displaying them in view, but i don't really know
You are shielding the actual username field on the User model with the related_name on the author ForeignKey.
It should be like this:
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="usernames")
'related_name=usernames' at plural.
The reason why it failed is because when you did:
user = User.objects.get(username=request.user.username)
you were basically accessing the reverse relation to the comments set that are tied to the user, not the actual username field (which I assume is a CharField).
More info about related_name in the django documentation.
I don't understand why you have set post and author to CharFields, when the model has foreign keys. Especially as you are setting then directly in the model anyway.
You should remove those definitions, and then exclude the fields from the form altogether:
class CommentsForm(forms.ModelForm):
class Meta:
model = PostComments
exclude = ("post", "author")
I'm working through https://bixly.com/blog/awesome-forms-django-crispy-forms/ , trying to set up a bootstrap 3 form using django crispy forms.
in app1/models.py, I have set up my form:
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import AbstractUser
from django import forms
class User(AbstractUser):
# Address
contact_name = models.CharField(max_length=50)
contact_address = models.CharField(max_length=50)
contact_email = models.CharField(max_length=50)
contact_phone = models.CharField(max_length=50)
......
Please note I have not created any db tables yet. I don't need them at this stage. I'm just trying to get the forms working. When I run this I get:
Performing system checks...
Unhandled exception in thread started by <function wrapper at 0x02B63EF0>
Traceback (most recent call last):
File "C:\lib\site-packages\django\utils\autoreload.py", line 222, in wrapper
fn(*args, **kwargs)
File "C:\lib\site-packages\django\core\management\commands\runserver.py", line 105, in inner_run
self.validate(display_num_errors=True)
File "C:\lib\site-packages\django\core\management\base.py", line 362, in validate
return self.check(app_configs=app_configs, display_num_errors=display_num_errors)
File "C:\lib\site-packages\django\core\management\base.py", line 371, in check
all_issues = checks.run_checks(app_configs=app_configs, tags=tags)
File "C:\lib\site-packages\django\core\checks\registry.py", line 59, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\lib\site-packages\django\contrib\auth\checks.py", line 12, in check_user_model
cls = apps.get_model(settings.AUTH_USER_MODEL)
File "C:\lib\site-packages\django\apps\registry.py", line 202, in get_model
return self.get_app_config(app_label).get_model(model_name.lower())
File "C:\lib\site-packages\django\apps\config.py", line 166, in get_model
"App '%s' doesn't have a '%s' model." % (self.label, model_name))
LookupError: App 'app1' doesn't have a 'models' model.
How can I fix this?
The AUTH_USER_MODEL settings should be of the form <app name>.<model>. Your model name is User, not model, so your setting should be:
AUTH_USER_MODEL = 'app1.User'
You should also remove the following User import from your models.py. You only have to import AbstractUser.
from django.contrib.auth.models import User
I read that this has to do with a circular dependency but I really couldn't found a workaround. I'm trying to get the number of Users(that belong to an organization) and maybe some more details related to Users but it seems that I can't really use the User model in the Organization model.
I also tried to reverse the get_users_count like return self.user_set.count() but that didn't work either.
Traceback
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/Manos/Projects/devboard/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/Users/Manos/Projects/devboard/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/Users/Manos/Projects/devboard/env/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/Manos/Projects/devboard/env/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/Users/Manos/Projects/devboard/env/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/Manos/Projects/devboard/project/accounts/models.py", line 3, in <module>
from project.organizations.models import Organization
File "/Users/Manos/Projects/devboard/project/organizations/models.py", line 5, in <module>
from project.accounts.models import User
ImportError: cannot import name User
Organization Model
from uuidfield import UUIDField
from django.db import models
from project.accounts.models import User
class Organization(models.Model):
id = UUIDField(primary_key=True, auto=True, db_index=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=200, unique=True)
website = models.URLField(max_length=200, blank=True)
def __str__(self):
return self.name
def get_users_count(self):
return User.objects.filter(organization=self).count()
User Model
class User(AbstractBaseUser):
id = models.AutoField(primary_key=True) # custom User models must have an integer PK
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
email = models.EmailField(max_length=255, unique=True, db_index=True)
organization = models.ForeignKey(Organization, related_name="users", null=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
Move the import into the get_users_count() method:
def get_users_count(self):
from project.accounts.models import User
return User.objects.filter(organization=self).count()
Or remove the import at all and use the backward relation:
def get_users_count(self):
return self.users.count()