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)
Related
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)
I am using djnago 11.1 ,python 2.7 and mongokit.i am making an application of django with mongodb and sql database.so first i does coding related to sql and my application run fine. But after coding for mongodb it is showing this error:-
After a dozen hours of troubleshooting, probably more, I thought I was finally in business, but then I got:
command prompt-
(orahienv) somya#somya-Inspiron-15-3555:~/Desktop/backup/admin_python$ python manage.py runserver
Performing system checks...
Unhandled exception in thread started by <function wrapper at 0x7fa8ce735de8>
Traceback (most recent call last):
File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
self.check(display_num_errors=True)
File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check
include_deployment_checks=include_deployment_checks,
File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks
return checks.run_checks(**kwargs)
File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config
return check_resolver(resolver)
File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver
return check_method()
File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 254, in check
for pattern in self.url_patterns:
File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 398, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/somya/Desktop/backup/admin_python/admin_python/urls.py", line 21, in <module>
url(r'', include('admin_app.urls', namespace = 'admin_app')),
File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 50, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/somya/Desktop/backup/admin_python/admin_app/urls.py", line 26, in <module>
exec "from {0} import {1}".format(dir_name + files.split(".")[0], files.split(".")[0].title())
File "<string>", line 1, in <module>
File "/home/somya/Desktop/backup/admin_python/admin_app/views_cluster/Travel_Details.py", line 30, in <module>
from models import Location
File "/home/somya/Desktop/backup/admin_python/models.py", line 15, in <module>
class AuthGroup(models.Model):
File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/base.py", line 118, in __new__
"INSTALLED_APPS." % (module, name)
RuntimeError: Model class models.AuthGroup doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
There is little info on this on the web, and no solution out there has resolved my issue. Any advice would be tremendously appreciated
setting.py-
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'admin_app',
'celery',
admin_python/model.py -
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.contrib.auth.signals import user_logged_in
import hashlib, os
from django.template.defaultfilters import default
from django.core.signals import setting_changed
from django.core.validators import MinValueValidator
import admin_python
import admin_app
from django.conf import settings
from django.contrib.auth.models import BaseUserManager
import string
import random
import datetime
from django_mongokit import connection
from django_mongokit.document import DjangoDocument
class Acsum(models.Model):
sum_from = models.IntegerField(blank=True, null=True)
sum_to = models.IntegerField(blank=True, null=True)
sum_date = models.DateTimeField(blank=True, null=True)
sum_amount = models.FloatField(blank=True, null=True)
sum_type = models.CharField(max_length=12, blank=True, null=True)
sum_reason = models.CharField(max_length=250, blank=True, null=True)
dd = models.IntegerField(db_column='ID', blank=True, null=True) # Field name made lowercase.
balance = models.CharField(max_length=100, blank=True, null=True)
tr_date = models.BigIntegerField(blank=True, null=True)
tr_month = models.BigIntegerField(blank=True, null=True)
tr_year = models.BigIntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'acsum'
class Location(DjangoDocument):
collection_name = 'location'
__database__ = 'pom'
structure = {
'user_id':int,
'name':basestring,
'loc_lon': float,
'timestamp':datetime.datetime,
'activity':basestring,
'lot_lat':float,
'battery_status':basestring,
'address':basestring,
'date_created':datetime.datetime
}
use_dot_notation = True
Something is horribly wrong with your project structure.
import admin_python
import admin_app
Are these 2 separate apps? if yes, then Why do you have .../admin_python/admin_app/... path?
if models.py is under admin_python directory you need to do following
add admin_python to INSTALLED_APPS
add the following to your all models
class Meta:
app_label = "admin_python"
The reason for this is usually that the model exists outside of the standard locations
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()
I am working on a Mezzanine Model, and want simply to send a SOAP request, and save that response as a file in a Django FileField, using code in the models.py.
I have seen the Django Documentation at https://docs.djangoproject.com/en/1.6/ref/models/fields/#django.db.models.FileField
I have read this- Django - how to create a file and save it to a model's FileField?
But still, I am getting the traceback...
File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 271, in get_model
self._populate()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 75, in _populate
self.load_app(app_name, True)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 99, in load_app
models = import_module('%s.models' % app_name)
File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/home/docker/hydroshare/timeSeriesApp/models.py", line 18, in <module>
class TimeSeries(Page, RichText, AbstractResource, models.Model):
File "/home/docker/hydroshare/timeSeriesApp/models.py", line 37, in TimeSeries
resource_file.save('My File', ContentFile('A string with the file content'))
AttributeError: 'FileField' object has no attribute 'save'
Here is my models.py-
from django.contrib.contenttypes import generic
from django.contrib.auth.models import User, Group
from django.db import models
from mezzanine.pages.models import Page, RichText
from mezzanine.core.models import Ownable
from hs_core.models import AbstractResource
from hs_core.models import resource_processor
from mezzanine.pages.page_processors import processor_for
from suds.client import Client
from django.core.files.base import ContentFile
from django.core.files import File
class TimeSeries(Page, RichText, AbstractResource, models.Model):
resource_description = models.TextField(null=False, blank=True, default='',
help_text ='I.E. Upper Provo River Flow',
)
resource_url = models.TextField(max_length=100,null=False, blank=True, default='',
help_text ="The WSDL Url for your web services- I.E. 'http://worldwater.byu.edu/interactive/dr/services/index.php/services/cuahsi_1_1.asmx?WSDL'"
)
resource_namespace=models.TextField(max_length=100,null=False, blank=True, default='',
help_text ='The namespace is probably {http://www.cuahsi.org/waterML/1.1/}'
)
resource_file = models.FileField(upload_to='Time Series File', null=True, blank=True)
###Suds Call###
client = Client(resource_url, cache=None)
response = client.service.GetValues() # a waterml file? (which is a type of xml file)
response.open
resource_file.save('Time Series File', File(response))
class Meta:
verbose_name = "Time Series"
processor_for(TimeSeries)(resource_processor)