I have these models below
# user profile models file
from ad.models import FavoriteAd
class UserProfile(models.Model):
def get_user_favorite_ad(self):
return FavoriteAd.objects.filter(fav_user=self)
# ad models file
from user_profile.models import UserProfile
class FavoriteAd(models.Model):
fav_user = models.ForeignKey(UserProfile, blank=False, on_delete=models.CASCADE)
I have tried using these but it give me the NameError UserProfile not found
# ad models files
class FavoriteAd(models.Model):
fav_user = models.ForeignKey('user_profile.UserProfile', blank=False, on_delete=models.CASCADE)
Also tried these as well still got error that model are not ready
# ad models files
from django.apps import apps
UserProfile = apps.get_model('user_profile', 'UserProfile')
class FavoriteAd(models.Model):
fav_user = models.ForeignKey(UserProfile, blank=False, on_delete=models.CASCADE)
You are using FavoriteAd inside get_user_favorite_ad method of
UserProfile model
Thats the reason you are unable to import it in FavoriteAd and this is causing circular import.
For fetching favorite ads of that user, Use favoritead_set to get related objects
# remove that import as well
# from ad.models import FavoriteAd
class UserProfile(models.Model):
def get_user_favorite_ad(self):
return self.favoritead_set.all()
Related
I don't have the advertisement module displayed in the django admin panel. Here is the model code
from django.db import models
class Advertisement(models.Model):
title = models.CharField(max_length=1000, db_index=True)
description = models.CharField(max_length=1000, default='', verbose_name='description')
creates_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
price = models.FloatField(default=0, verbose_name="price")
views_count = models.IntegerField(default=1, verbose_name="views count")
status = models.ForeignKey('AdvertisementStatus', default=None, null=True, on_delete=models.CASCADE,
related_name='advertisements')
def __str__(self):
return self.title
class Meta:
db_table = 'advertisements'
ordering = ['title']
class AdvertisementStatus(models.Model):
name = models.CharField(max_length=100)
admin.py /
from django.contrib import admin
from .models import Advertisement
admin.site.register(Advertisement)
I was just taking a free course from YouTube. This was not the case in my other projects. Here I registered the application got the name in INSTALLED_APPS. Then I performed the creation of migrations and the migrations themselves. Then I tried to use the solution to the problem here , nothing helped. I didn't find a solution in Google search either.
127.0.0.1:8000/admin/
console
admins.py
The name of the file is admin.py not admins.py. Yes, that is a bit confusing since most module names in Django are plural. The rationale is probably that you define a (single) admin for the models defined.
Alternatively, you can probably force Django to import this with the AppConfig:
# app_name/apps.py
from django.apps import AppConfig
class AppConfig(AppConfig):
def ready(self):
# if admin definitions are not defined in admin.py
import app_name.admins # noqa
Hello kings and queens!
I'm working on a project and got stuck on a (for me) complicated issue. I have one model (generalpage.models) where all the common info about the users is stored. In a different app (profilesettings), I have an app where all profile page related functions will be coded.
I tried to inherit the model fields from the User class in generalpage.models into profilesettings.models by simply writing UserProfile(User). When I did this, a empty forms was created in the admin panel. So basically, the information that was already stored generalpage.models were not inherited into the profilesettings.models, I created an entire new table in the database.
my questions are:
Is it possible to create an abstract class for a custom user model?
Is there a proper way to handle classes and create a method in profilesettings.models that fills the UserProfile form with the data already stored in database created by the User class?
Can someone please explain how the information can be passed from one application to another without creating a new empty form?
Filestructure:
Admin panel:
generalpage.models:
from random import choices
from secrets import choice
from unittest.util import _MAX_LENGTH
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, User, PermissionsMixin
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from generalpage.managers import CustomUserManager
from django.conf import settings
from generalpage.managers import CustomUserManager
# Create your models here.
sex_choices = ( ("0", "Man"),
("1", "Kvinna"),
("2", "Trans")
)
class User(AbstractBaseUser, PermissionsMixin):
user = models.CharField(settings.AUTH_USER_MODEL, null=True, max_length=50)
username = models.CharField(_("Användarnamn"), max_length=100, null=True, unique=True)
age = models.IntegerField(_("Ålder"),null=True, blank=False)
email = models.EmailField(_("E-mail"), unique=True, null=False)
country = models.CharField(_("Land"),max_length=50, null=True, blank=True)
county = models.CharField(_("Län"),max_length=50, null=True, blank=True)
city = models.CharField(_("Stad"),max_length=50, null=True, blank=True)
sex = models.CharField(_("Kön"), choices=sex_choices, null=True, blank=False, max_length=50)
profile_picture = models.ImageField(_("Profilbild"),null=True, blank=True, default="avatar.svg", upload_to = "static/images/user_profile_pics/")
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
USERNAME_FIELD = 'username' # defines the unique identifier for the User model
REQUIRED_FIELDS = ["email"] # A list of the field names that will be prompted for when creating a user via the createsuperuser management command
objects = CustomUserManager()
def __str__(self):
return self.username
profilesettings.models:
from generalpage.models import User, UserInfo, Room, Message, Topic
from django.db import models
class UserProfile(User):
pass
class Settings(UserInfo):
pass
My models after #viktorblindh suggestion are:
for admin.py:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from profilesettings.models import UserProfile
from generalpage.models import User
class UserProfileInline(admin.StackedInline):
model = UserProfile
min_num = 1
class UserProfileAdmin(BaseUserAdmin):
inlines = [UserProfileInline, ]
admin.site.register(User, UserProfileAdmin)
# admin.site.register(UserProfile)
# admin.site.register(Settings)
and for profilesettings.models:
from generalpage.models import User, UserInfo, Room, Message, Topic
from django.db import models
from django.conf import settings
class UserProfile(User):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Settings(UserInfo):
pass
```
The solution suggested in:
https://stackoverflow.com/questions/42424955/how-to-exchange-data-between-apps-in-django-using-the-database
solved my issue.
Maybe i'm misunderstanding the issue at hand but to me it sounds like you would want to have a OneToOne key on your profilesettings.UserProfile to your generalpage.user. I'm assuming every user have their own unique profilesettings.
from django.conf import settings
class UserProfile(User):
user(models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
Then after that you can use an inlineformset in your generalpage.admin to get all the information displayed in the same form.
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from profilesettings.models import UserProfile
class UserProfileInline(admin.StackedInline):
model = UserProfile
min_num = 1
class UserProfileAdmin(BaseUserAdmin):
inlines = [UserProfileInline, ]
admin.site.register(User, UserProfileAdmin)
I'm trying to create a system, for a User to worte a comment on an other User. So I create a models with GenericRelation like this:
App1\models.py:
from django.contrib.auth.models import AbstractUser
from django.contrib.contenttypes.fields import GenericRelation
from app2.models import Social
class User(AbstractUser):
"""
Default User model used for authentification system
"""
relation = GenericRelation(Social) # recently added
App2\models.py:
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from app1.models import User
class Social(models.Model):
content_object = GenericForeignKey('content_type', 'object_id')
object_id = models.PositiveIntegerField()
content_type = models.ForeignKey(ContentType,
on_delete=models.CASCADE)
author= models.ForeignKey(User, # Member who wrote the message
on_delete=models.CASCADE,
related_name='wrote')
message= models.TextField()
Before adding the field relation in User. I don't have any problem but I was remake the work of GenericRelation and I want to simplify my cod.
Then the problem appear when i run the server. I'm in a recursive import loop...
file .\app2\models.py
from app2.models import Social
file .\app1\models.py
from app1.models import User
Would there be a possibility of solving this problem by keeping a GenericRelation on Social and GenericRelation for my User?
Because after I want to add an other GenericRelation(Social) on an other model/
Try to reference User model as string in ForeignKey, like so:
author = models.ForeignKey(
'app1.User',
on_delete=models.CASCADE,
related_name='wrote')
)
And, also, remove from app1.models import User.
When I try to migrate my code I get this error.
Here are my code and classes:
from django.db import models
from core.models import Event
class TicketType(models.Model):
name = models.CharField(max_length=45)
price = models.DecimalField(max_length=2, decimal_places=2, max_digits=2)
type = models.CharField(max_length=45)
amount = models.IntegerField()
event = models.ForeignKey(Event)
class Meta:
app_label = "core"
import datetime
from django.core.serializers import json
from django.db import models
from core.models import User
class Event(models.Model):
page_attribute = models.TextField()
name = models.TextField(max_length=128 , default="New Event")
description = models.TextField(default="")
type = models.TextField(max_length=16)
age_limit = models.IntegerField(default=0)
end_date = models.DateTimeField(default=datetime.datetime.now())
start_date = models.DateTimeField(default=datetime.datetime.now())
is_active = models.BooleanField(default=False)
user = models.ForeignKey(User)
ticket_type=models.ForeignKey('core.models.ticket_type.TicketType')
class Meta:
app_label = "core"
Here is the error I get:
CommandError: One or more models did not validate:
core.event: 'ticket_type' has a relation with model core.models.ticket_type.TicketType,
which has either not been installed or is abstract.
You're unnecessarily confusing yourself by having these in separate files within the same app.
But your issue is caused by the way you're referenced the target model. You don't use the full module path to the model: you just use 'app_name.ModelName'. So in your case it should be:
ticket_type=models.ForeignKey('core.TicketType')
Another issue can be when using multiple models in separate files missing statement like:
class Meta:
app_label = 'core_backend'
You can also get this error if there a bug in your models file that prevents it from loading properly. For example, in models.py
from third_party_module_i_havent_installed import some_method
I hit this error when I didn't put a third-party app in my INSTALLED_APPS setting yet.
I have made a custom profile model which looks like this:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.ForeignKey('User', unique=True)
name = models.CharField(max_length=30)
occupation = models.CharField(max_length=50)
city = models.CharField(max_length=30)
province = models.CharField(max_length=50)
sex = models.CharField(max_length=1)
But when I run manage.py syncdb, I get:
myapp.userprofile: 'user' has a relation with model User, which has
either not been installed or is abstract.
I also tried:
from django.contrib.auth.models import BaseUserManager, AbstractUser
But it gives the same error. Where I'm wrong and how to fix this?
Exactly in Django 1.5 the AUTH_USER_MODEL setting was introduced, allowing using a custom user model with auth system.
If you're writing an app that's intended to work with projects on Django 1.5 through 1.10 and later, this is the proper way to reference user model (which can now be different from django.contrib.auth.models.User):
class UserProfile(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
See docs for more details.
In case you're writing a reusable app supporting Django 1.4 as well, then you should probably determine what reference to use by checking Django version, perhaps like this:
import django
from django.conf import settings
from django.db import models
def get_user_model_fk_ref():
if django.VERSION[:2] >= (1, 5):
return settings.AUTH_USER_MODEL
else:
return 'auth.User'
class UserProfile(models.Model):
user = models.ForeignKey(get_user_model_fk_ref())
Change this:
user = models.ForeignKey('User', unique=True)
to this:
user = models.ForeignKey(User, unique=True)