Let's say I have AssetUser model looks like follow.
class AssetUser(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
my query set looks like follow.
qs = User.objects.get(pk=1)
when i run qs.assetuser_set i am getting error like follow.
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'User' object has no attribute 'assetuser_set'
what mistake i made here.
Django models should be inherited from Model class, so you need to change your code to this:
class AssetUser(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
Related
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.
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')
theres's something I'm missing or don't understand, maybe a very basic concept.
I have two models Person and Student, related by a OneToOneField like this:
class Student(models.Model):
person = models.OneToOneField(
Person,
on_delete = models.CASCADE,
)
# fields definition
Should't I be able to access Student from Person with student_set?
Like this, but I get de error as follows:
>>> from people.models import Person
>>> p = Person.objects.get(pk=6)
>>> p.student_set.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Person' object has no attribute 'student_set'
>>>
Thanks!
The answer you are looking for is literally in the term "One to One relationship", there is not set returned here but a direct relationship.
p.student is going to access the student object related the person
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
This seems like a really trivial question, but it is killing me.
models.py
class Location(models.Model):
place = models.CharField("Location", max_length=30)
[...]
class Person(models.Model):
first = models.CharField("First Name", max_length=50)
[...]
location = models.ManyToManyField('Location')
From the shell:
>>> from mysite.myapp.models import *
>>> p = Person.objects.get(id=1)
>>> p
<Person: bob >
>>> l = Location(place='123 Main')
>>> p.location_set.add(l)
>>> p.save()
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Person' object has no attribute 'location_set'
I'm really not seeing what I'm missing.
Shouldn't you be using p.location.add()? location_set or <modelname>_set is the default name for the reverse lookup for that model.
location_set would be the default name for a backward relation, however since you've defined the ManyToManyField on the Person model, you can access the related manager via the field name:
p.location.add(l)
With this in mind, it makes more sense to name the ManyToManyField as a pluralised noun, e.g.
class Person(models.Model):
first = models.CharField("First Name", max_length=50)
[...]
locations = models.ManyToManyField('Location')
Also, from memory, when you try to add model instances to a many-to-many relationship, the instance must be saved prior to adding.