System check identified 3 issues (0 silenced) - django

what could the issue with my model.py .i have tried everything nothing happens.and i think i defined my foreign key the right way .could it be a problem with my defining or do i have to use memberid.user in my foreginkey or what would be effect.any contribution is welcomed.
Performing system checks...
Unhandled exception in thread started by <function wrapper at 0x7f6a926d69b0>
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
self.check(display_num_errors=True)
File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 405, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
tithe.tithe.memberid: (fields.E300) Field defines a relation with model 'memberid', which is either not installed, or is abstract.
tithe.tithe.memberid: (fields.E307) The field tithe.tithe.memberid was declared with a lazy reference to 'tithe.memberid', but app 'tithe' doesn't provide model 'memberid'.
tithe.tithe: (models.E012) 'unique_together' refers to the non-existent field 'IntegerField'.
System check identified 3 issues (0 silenced).
Performing system checks...
Unhandled exception in thread started by <function wrapper at 0x7f3d3ccdc9b0>
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
self.check(display_num_errors=True)
File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 405, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
tithe.tithe.memberid: (fields.E300) Field defines a relation with model 'User', which is either not installed, or is abstract.
tithe.tithe.memberid: (fields.E307) The field tithe.tithe.memberid was declared with a lazy reference to 'tithe.user', but app 'tithe' doesn't provide model 'user'.
tithe.tithe: (models.E012) 'unique_together' refers to the non-existent field 'IntegerField'.
this my model.py code
from django.utils import timezone
from django.db import models
# Create your models here.
class tithe(models.Model):
memberid = models.ForeignKey('User')
membername = models.CharField(max_length=45)
receitcode = models.CharField(max_length=45)
tithes = models.IntegerField()
combinedoffering = models.IntegerField()
campmeetingoffering = models.IntegerField()
churchbuilding = models.IntegerField()
conference = models.IntegerField()
localchurch = models.IntegerField()
funds = models.IntegerField()
total = models.IntegerField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.receitcode
class Meta:
unique_together = ["receitcode","IntegerField"]
ordering = ["published_date","membername"]

The line below
memberid = models.ForeignKey('User')
is causing the problem. You have to pass a User object to it.
Import User model.
from django.contrib.auth.models import User
then
memberid = models.ForeignKey(User)

The first two warnings are because Django cannot find the model 'User' that you refer to in the memberid foreign key.
I recommend you use settings.AUTH_USER_MODEL to reference the user model. This will work whether or not you have a custom user model.
memberid = models.ForeignKey(settings.AUTH_USER_MODEL)
See the docs for more info on referencing the user model.
Note that it would be better to call name your field member. That way, the related instance will be member and the related id will be member_id. At the moment, the related instance is memberid, and the related id is memberid_id.
The final warning is because you do not have a field IntegerField in the model. If you want the receitcode field to be unique by itself, then remove the unique_together line and change the field to:
receitcode = models.CharField(max_length=45, unique=True)

Your ForeignKey needs to reference a concrete model or abstract model. Since you are referencing using a string (which means the model is abstract) you need to declare the class Meta: as abstract by stating abstract = True
Relationships defined this way on abstract models are resolved when the model is subclassed as a concrete model and are not relative to the abstract model’s app_label:
The below information is from the Django Documentation https://docs.djangoproject.com/en/1.11/ref/models/fields/
products/models.py
from django.db import models
class AbstractCar(models.Model):
manufacturer = models.ForeignKey('Manufacturer', on_delete=models.CASCADE)
# This is what you need to add
class Meta:
abstract = True

Related

Select2 on explicit through model in Django admin

Using autocomplete_fields/search_fields in Django's admin works well to cause a Select2 widget to be used for a ForeignKey field, but I'm getting an error when I set things up to have Select2 widgets rendered on a declared through model in a ManyToManyField relationship. My models are different than the following, but using the example from the Django docs where through models in the admin are discussed as a starting point, I have things set up something like this (the example in the docs has an implicit through model, but I have an explicitly declared through model):
class Person(models.Model):
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership', related_name='groups')
class Membership(models.Model):
person = models.ForeignKey('Person', ...)
group = models.ForeignKey('Group', ...)
and in admin.py:
class PersonAdmin(admin.ModelAdmin):
inlines = [MembershipInline,]
search_fields = ('first_name','last_name,)
class MembershipInline(admin.TabularInline):
model = Membership
autocomplete_fields = ('person',)
class GroupAdmin(admin.ModelAdmin):
inlines = [MembershipInline,]
When I go to the GroupAdmin and try to create a membership, the Select2 widget is rendered, but when I try to look up a person, I get this error:
Forbidden (Permission denied): /admin/autocomplete/
Traceback (most recent call last):
File "/virtualenvs/my_virtualenv/lib/python3.8/site-packages/django/utils/datastructures.py", line 84, in __getitem__
list_ = super().__getitem__(key)
KeyError: 'app_label'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/virtualenvs/my_virtualenv/lib/python3.8/site-packages/django/contrib/admin/views/autocomplete.py", line 79, in process_request
app_label = request.GET["app_label"]
File "/virtualenvs/my_virtualenv/lib/python3.8/site-packages/django/utils/datastructures.py", line 86, in __getitem__
raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'app_label'
I am using django-jazzmin, so the problem COULD be caused by it, but the Select2 widgets work fine in ForeignKey relationships that are not part of a through model. Someone encountered something similar in Grappelli a year ago, but I can't tell whether this problem is similar.
Any help is very much appreciated.

How to import export works in foreign key - django

I do have two models 1) patient profile, to get patient First and last name, default id and 2) Medinfo, medical information of patient used default id of patient model as foreign key.
I am trying to use django import export for bulk upload data.. in patient profile model i can able to upload data without any trouble, but when I trying upload data in medinfo model, I am getting error. I do understand due to using foreinkey as field I am getting trouble here to import data. How to do it?
Note: pat_ID is also a primary key of Medinfo model.
class Patientprofile(models.Model):
pat_Fname = models.CharField(max_length=100)
pat_Lname = models.CharField(max_length=100, blank=True)
def __str__(self):
return str(self.id)
class MedInfo(models.Model):
# Medical Information fields
Notes = models.TextField(max_length=2000, blank=True)
pat_ID = models.OneToOneField(patientprofile, on_delete=models.CASCADE,unique=True, primary_key=True)
def __int__(self):
return self.pat_ID
Error:
Line number: 1 - 'id'
, 32.0
Traceback (most recent call last):
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\import_export\resources.py", line 661, in import_row
instance, new = self.get_or_init_instance(instance_loader, row)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\import_export\resources.py", line 353, in get_or_init_instance
instance = self.get_instance(instance_loader, row)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\import_export\resources.py", line 340, in get_instance
import_id_fields = [
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\import_export\resources.py", line 341, in <listcomp>
self.fields[f] for f in self.get_import_id_fields()
KeyError: 'id'

django - ValueError: <model> needs to have a value for field "id" before this many-to-many relationship can be used

Say, I have a model Post which has many to many relation to built-in User for liked_post
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
like = models.ManyToManyField(User, related_name='liked_posts')
All is going nice for the logic, I can add/remove the like relation nicely.
But when I introduce additional attribute save for saved_post, like this:
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
like = models.ManyToManyField(User, related_name='liked_posts')
save = models.ManyToManyField(User, related_name='saved_posts')
It always throw an error below when I'm trying to even instantiate the Post model.
ValueError: "<Post: Post object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used.
Note that I did not even modify/add any custom save() method.
The error just pops up even when I'm trying to call p = Post.object.create().
From what I have known, I need to save Post first before adding any like or save relation. But I got error even from saving a Post instance.
====
Edit 1
Include a full stack trace:
Error
Traceback (most recent call last):
File "/home/rahmat/Upworks/06_Made_Gatewee/gatewee/app_post/tests/test_post_save.py", line 34, in setUp
p = Post.objects.create()
File "/home/rahmat/Upworks/06_Made_Gatewee/gatewee/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/rahmat/Upworks/06_Made_Gatewee/gatewee/venv/lib/python3.6/site-packages/django/db/models/query.py", line 422, in create
obj.save(force_insert=True, using=self.db)
File "/home/rahmat/Upworks/06_Made_Gatewee/gatewee/venv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 527, in __get__
return self.related_manager_cls(instance)
File "/home/rahmat/Upworks/06_Made_Gatewee/gatewee/venv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 840, in __init__
(instance, self.pk_field_names[self.source_field_name]))
ValueError: "<Post: Post object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used.
The problem here is that the save field in Post model conflicts with the internal save method and cause this error.
Simply changed the field name, like:
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
like = models.ManyToManyField(User, related_name='liked_posts')
saved_posts = models.ManyToManyField(User, related_name='saved_posts')

Django 1.8 and nose: conflicting models?

I have a Django application I recently upgraded to Django 1.8.4. I'm using nose 1.3.7 and django-nose 1.4.1 for my test runner to run over 200 integration and unit tests. Since upgrading both Django and nose, I'm finding that 12 of my tests fail with this same error:
======================================================================
ERROR: Failure: RuntimeError (Conflicting 'c' models in application 'nose': <class 'account.tests.form_tests.TestAddress'> and <class 'nose.util.C'>.)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/me/venv/myproj/lib/python2.7/site-packages/nose/loader.py", line 523, in makeTest
return self._makeTest(obj, parent)
File "/Users/me/venv/myproj/lib/python2.7/site-packages/nose/loader.py", line 568, in _makeTest
obj = transplant_class(obj, parent.__name__)
File "/Users/me/venv/myproj/lib/python2.7/site-packages/nose/util.py", line 644, in transplant_class
class C(cls):
File "/Users/me/venv/myproj/lib/python2.7/site-packages/django/db/models/base.py", line 311, in __new__
new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
File "/Users/me/venv/myproj/lib/python2.7/site-packages/django/apps/registry.py", line 223, in register_model
(model_name, app_label, app_models[model_name], model))
RuntimeError: Conflicting 'c' models in application 'nose': <class 'account.tests.form_tests.TestAddress'> and <class 'nose.util.C'>.
What's curious is that the form_tests.py module doesn't even reference TestAddress which is actually a class inside my "profiles" model:
# myprof/profile/models.py
class TestAddress(models.Model):
user = models.OneToOneField(User, primary_key=True, unique=True)
address_line_1 = models.CharField(max_length=30)
address_line_2 = models.CharField(max_length=30, null=True, blank=True)
city = models.CharField(max_length=30)
region = models.CharField(max_length=30, null=True, blank=True)
postal_code = models.CharField(max_length=10, null=True, blank=True)
country = models.ForeignKey('Country')
class Meta:
db_table = 'test_address'
def __unicode__(self):
return u'%s' % (self.user.username)
When my tests need to generate an instance of the TestAddress class, I use a factory_boy (v. 2.5.2) factory:
# utils/factories.py
from profile.models import TestAddress
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
username = 'testuser'
class TestAddressFactory(factory.django.DjangoModelFactory):
class Meta:
model = TestAddress
user = factory.SubFactory('utils.factories.UserFactory')
address_line_1 = '123 Main St.'
address_line_2 = 'Apt. A'
city = 'AnyCity'
region = 'AnyRegion'
postal_code = '12345'
country = factory.SubFactory('utils.factories.CountryFactory')
I set breakpoints in the nose loader.py module and confirmed that loader sees "TestAddress" in "profile.models". However, there is a "parent.__name__" variable there which is set to "account.tests.model_tests". I have a couple of questions:
1. Why is this occurring?
2. Is there a way I can fix it?
3. Is there some way I can get nose to tell me which tests are resulting in these runtime errors so that I can at least disable them if I can't fix the problem?
I set "--verbosity=2" but that
doesn't display the names of failing tests. I looked through the nose docs and didn't see anything. Worst case I can write a script to call every test individually and echo the test name before running it but that seems very ugly and time-consuming.
Thanks.
I ran into the same issue while porting my Django project from 1.6 to 1.8 and updating django-nose to 1.4.3.
It appears that with the new DiscoverRunner used in 1.7 onwards, django-nose attempts to run all classes beginning with Test* as Test Cases, which leads to them being adapted into django-nose's django app before they are encountered in test modules.
I managed to resolve this issue by renaming them to avoid this naming scheme, to things like AdressTestModel.
I just encountered this and solved it with the #nottest decorator.
Technically, it's for functions according to the docs, but decorating classes with it also works:
from nose.tools import nottest
#nottest
class TestAddressFactory(...):
...
All the decorator does is add __test__ with the value True to the object it is decorating.
def nottest(func):
"""Decorator to mark a function or method as *not* a test
"""
func.__test__ = False
return func

Get and set ForeignKey directly in Django

I'm trying to work with Django model created from a mysql database which has composite foreign keys.
My models.py goes like this.
class Make(models.Model):
idmake = models.IntegerField(primary_key=True)
make = models.CharField(max_length=20L, unique=True, blank=True)
def __unicode__(self):
return self.make
class Meta:
db_table = 'make'
class Models(models.Model):
idmodels = models.IntegerField(primary_key=True, unique=True)
make = models.ForeignKey(Make, db_column='make', to_field='make')
model = models.CharField(max_length=45L, unique=True)
resource_type = models.CharField(max_length=7L)
def __unicode__(self):
return self.model
class Meta:
db_table = 'models'
class Systems(models.Model):
idsystems = models.IntegerField(primary_key=True, unique=True)
make = models.ForeignKey(Models, null=True, db_column='make', blank=True, related_name='system_make')
model = models.ForeignKey(Models, null=True, db_column='model', to_field = 'model', blank=True, related_name='system_model')
serial_num = models.CharField(max_length=45L, blank=True)
service_tag = models.CharField(max_length=45L, blank=True)
mac = models.CharField(max_length=45L, unique=True)
Now when I try to access the make field of Systems I get a ValueError.
>>> s = Systems.objects.get(pk=1)
>>> s.model
<Models: model11>
>>> s.model.make
<Make: make1>
>>> s.make
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/django/db/models/fields/related.py", line 384, in __get__
rel_obj = qs.get(**params)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 395, in get
clone = self.filter(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 669, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 687, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1271, in add_q
can_reuse=used_aliases, force_having=force_having)
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1202, in add_filter
connector)
File "/usr/lib/python2.7/site-packages/django/db/models/sql/where.py", line 71, in add
value = obj.prepare(lookup_type, value)
File "/usr/lib/python2.7/site-packages/django/db/models/sql/where.py", line 339, in prepare
return self.field.get_prep_lookup(lookup_type, value)
File "/usr/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1003, in get_prep_lookup
return super(IntegerField, self).get_prep_lookup(lookup_type, value)
File "/usr/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 322, in get_prep_lookup
return self.get_prep_value(value)
File "/usr/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 997, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'make1'
I'm not allowed to change the tables and relations in the database. I'm very new to Django and I'm unable to figure out what is the correct fix for this issue. Basically I would like to be able to get and set the make field of the Systems model directly. Can someone guide me on how I should go about doing this? My initial thoughts were that I would have to create a custom ForeignKey field.
I suspect your codes don't match your DB schema. In this line:
make = models.ForeignKey(Models, null=True, db_column='make', blank=True, related_name='system_make')
Models is supposed to be Make, isn't it? And your Systems.model has to_field = 'model', did you miss to_field='make' for Systems.make? I suggest you to drop the whole DB, run syncdb and create test data again. Then see if the error still happen.
Some more tips for your code:
as your defined to_field = 'model' and to_field='make', you'd better to consider add db_index=True for make and model fields. Otherwise query performance may be bad when your dataset is large
if you're going to set Make.make and Models.model to be unique and indexed, they seems to be qualified as primary key. Are the idmake and idmodels really necessary in your case?
primary_key=True guarantees unique. unique=True is redundant
Django conversions use singular form for model definition. I.e., use Model System, rather than Models Systems. Also, usually we use id, rather than idmake, idmodels. Those are just conversions, up to you
I discovered the answer, rather by accident. Would like to share for anyone facing similar problem.
To access make directly from Systems
>>> s = Systems.objects.get(pk=1)
>>> s.model
<Models: model11>
>>> s.model.make
<Make: make1>
>>> s.make_id
u'make1'
To set make directly from a Systems object
>>> s.make_id = Models.objects.get(model='model21').make.make
>>> s.save()
>>> s.make_id
u'make2'
Be warned. This will not work if the get method of Models returns multiple or no model objects. For example if my Models table was as:
then
>>>> Models.objects.get(model='unknown').make.make
Traceback (most recent call last):
....
MultipleObjectsReturned: get() returned more than one Models -- it returned 2!
>>> Models.objects.get(model='not known').make.make
Traceback (most recent call last):
....
DoesNotExist: Models matching query does not exist.
I fell the programmer needs to be cautious about these things.
EDIT
From comments by #ZZY to this answer and to his own answer
class Models(models.Model):
idmodels = models.IntegerField(primary_key=True, unique=True)
make = models.ForeignKey(Make, db_column='make', to_field='make')
model = models.CharField(max_length=45L, unique=True)
resource_type = models.CharField(max_length=7L)
def __unicode__(self):
return self.model
class Meta:
db_table = 'models'
unique_together = ("make", "model")
And also since model field in Models is unique, the scenario described by me should not occur in a correct table