I have nested models with OneToOneFields and want to have an InlineModelAdmin form in one ModelAdmin to point to a nested model...
models.py:
class User(models.Model):
username = models.CharField(max_length=128)
password = models.charField(max_length=128)
class IdentityProof(models.Model):
user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='proof')
proof_identity = models.FileField(upload_to='uploads/%Y/%m/%d/')
class Company(models.Model):
user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='company')
name = models.CharField(max_length=128)
class Person(models.Model):
user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='person')
name = models.CharField(max_length=128)
admin.py:
class IdentityProofInline(admin.TabularInline):
model = IdentityProof
#admin.register(Company)
class CompanyAdmin(admin.ModelAdmin):
inlines = [IdentityProofInline]
#admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
inlines = [IdentityProofInline]
For CompanyAdmin or PersonAdmin, I want to show its User's IdentityProof. How can I do that ?
I tried to use fk_name = 'user_proof or other combinations but it doesn't work...
Thanks.
This is not possible without an external package.
See Django Nested Inline and Django Nested Admin
Related
I have 2 many to many fields in models and i want to connect them to each other i mean if i connect user in Admin Model with Counter Party i cant see that in Counter Party admin
How can i do that?
When im trying to do that it shows only in 1 model
models.py
class CustomUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='Пользователь')
user_counter = models.ManyToManyField('CounterParty', blank=True, verbose_name='Контрагенты пользователя')
def __str__(self):
return f'{self.user}'
class CounterParty(models.Model):
GUID = models.UUIDField(default=uuid.uuid4, editable=True, unique=True)
name = models.CharField(max_length=150, verbose_name='Наименование')
customer = models.BooleanField(default=False, verbose_name='Заказчик')
contractor = models.BooleanField(default=False, verbose_name='Подрядчик')
counter_user = models.ManyToManyField(User, blank=True, related_name='counter_user',
verbose_name='Пользователи контрагента')
class Meta:
verbose_name = 'Контрагент'
verbose_name_plural = 'Контрагенты'
def __str__(self):
return
admin.py
from django.contrib import admin
from .models import CustomUser, CounterParty, ObjectList, SectionList
from authentication.models import User
from authentication.admin import UserAdmin
class CustomUserInLine(admin.StackedInline):
model = CustomUser
can_delete = False
verbose_name_plural = 'Пользователи'
class CustomUserAdmin(UserAdmin):
inlines = (CustomUserInLine,)
#admin.register(CounterParty)
class CounterPartyAdmin(admin.ModelAdmin):
pass
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
user admin
counter party admin
You would not want to have these kinds of references with ManyToMany. Ideally you would have a one sided reference.
You can do an inline in your admin like this:
class CustomUserInLine(admin.StackedInline):
model = "CustomUser.user_counter.through"
Here are the docs for inline M2M in the admin: Django docs
I am creating the super user through admin panel or command line, but it is not showing in the custom model in the database.
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
description = models.TextField(null=True)
profile_image = models.ImageField(null=True, blank=True)
def __str__(self):
return str(self.user)
class Following(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
following = models.CharField(max_length=30)
class Follower(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
follower = models.CharField(max_length=30)
Using OneToOnefield should create the user in the Profile model automatically but it is not happening. I am not sure what is wrong because in the previous project it was workiing fine. Also I have registered the models in admin.py.
I have a UserProfile where the User chose a language. Users should have the possibility to chose more than one language so i tried to use a ManyToManyField like so:
class Choices(models.Model):
languages = models.CharField(choices=settings.LANGUAGES, max_length=3)
def __unicode__(self):
return self.languages
class UserProfile(models.Model):
user = models.OneToOneField(User, null=True)
language = models.ManyToManyField(Choices)
in my form.py i did:
class UserProfileForm(forms.ModelForm):
language = forms.MultipleChoiceField(required=False, choices=settings.LANGUAGES)
class Meta:
model = UserProfile
fields=[
'Pictures',
.....
]
The problem is: The choices are shown in the template but in the admin the ManyToManyField is empty. So the Form works but the Model does not. Can somebody tell me why no Options are displayed? Where is the mistake at the M2M?
I have a website built in Django 1.10. The site has 3 different apps: teams, members and news.
The first app, called teams has one model called Team.
This is the Team/models.py:
from django.db import models
from django.db.models.signals import pre_save
from django.utils.text import slugify
class Team(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
slug = models.CharField(max_length=255, default='team', editable=True)
class Meta:
ordering = ('name',)
def __unicode__(self):
return self.name
The second app, called members has one model called Member.
This is the Member/models.py:
from django.db import models
class Piloto(models.Model):
name = models.CharField(max_length=255)
biography = models.TextField()
slug = models.CharField(max_length=255, default='piloto', editable=True)
class Meta:
ordering = ('name',)
def __unicode__(self):
return self.name
What I want is include the name of the team inside the member profile, so I know it should be something like:
team_of_member = models.ForeignKey();
But I don't know what to put in the parenthesis or how to import the model of the team to the model of the member. I was following the documentation of Django 1.10 but it wasn't working, also I've tried this link but it doesn't work. Could you give a hand? Thanks
Edit:
I tried to do as #Bulva was suggesting, so my code is now like this:
from django.db import models
from equipos.models import Team
class Member(models.Model):
name = models.CharField(max_length=255)
team = models.ForeignKey('teams.Team', null=True)
biography = models.TextField()
slug = models.CharField(max_length=255, default='piloto', editable=True)
class Meta:
ordering = ('name',)
def __unicode__(self):
return self.name
What you want is to provide the teams the member is a member of. It all depends on your business logic. A team has many members by definition, but can a member be a part of many teams? If yes, you have a many-to-many relationship. If no, you have a one-to-many relationship.
Under one-to-many assumption, the foreignkey information has to be put in the referenced model. Then:
from django.db import models
from team.models import Team # Generally, apps are in all lower-case (assuming your app is called team)
class Member(models.Model):
name = models.CharField(max_length=255)
team = models.ForeignKey('team.Team', related_name = 'members', null=True) # Do not forget to put team.Team inside a pair of single-quotes.
biography = models.TextField()
slug = models.CharField(max_length=255, default='piloto', editable=True)
class Meta:
ordering = ('name',)
def __unicode__(self): # use def __str__(self): in Python 3+
return self.name
In your view, you can then say this:
albert_team = albert.team
albert_teammates = albert_team.members
Under Many-to-Many assumption, it is more natural to capture the relationship in the team model:
from django.db import models
from django.db.models.signals import pre_save
from django.utils.text import slugify
class Team(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
slug = models.CharField(max_length=255, default='team', editable=True)
members = models.ManyToManyField('team.Member', related_name = 'teams')
class Meta:
ordering = ('name',)
def __unicode__(self):
return self.name
In views.py:
albert_teams = albert.teams
all_albert_teammates = []
for team in albert_teams:
all_albert_teammates.append(team.members)
Try this:
from teams.models import Team
# in the member model field
team_of_member = models.ForeignKey(Team);
In order to do what you want (assuming the code provided is your full "problematic" code) you should:
In Member/models.py:
from django.db import models
from teams.models import Team # <--add this line
class Piloto(models.Model):
name = models.CharField(max_length=255)
team_of_member = models.ForeignKey(Team, on_delete=models.CASCADE); # <--add this line
biography = models.TextField()
slug = models.CharField(max_length=255, default='piloto', editable=True)
class Meta:
ordering = ('name',)
def __unicode__(self):
return self.name
After you do this, remember to:
python manage.py makemigrations
python manage.py migrate
to change your models state.
Good luck :)
I have an abstract model that all my other models inherit from, it looks like this.
class SupremeModel(models.Model):
creator = models.ForeignKey(User, related_name="%(class)s_creator")
created = models.DateTimeField(null=True, blank=True)
deleted = models.BooleanField(default=False)
modified = models.DateTimeField(null=True,blank=True)
class Meta:
abstract = True
I then have a bunch of other models that inherit from this model, with something along these lines...
class ExampleModel(SupremeModel):
name = models.TextField(null=False, blank=False)
description = models.TextField(null=False, blank=False)
class AnotherModel(SupremeModel):
title = models.TextField(null=False, blank=False)
location = models.TextField(null=False, blank=False)
I want to create a Django model form for nearly all of my custom models that look similar to ExampleModel, but I always want the fields in SupremeModel to be excluded in the form...
How can I create a ModelForm that can be used to inherit the exclude parameters that will hide creator,created,deleted, and modified but show all of the other fields (in this case name and description or title and location).
you may try this
class ExcludedModelForm(ModelForm):
class Meta:
exclude = ['creator', 'created', 'deleted', 'modified']
class ExampleModelForm(ExcludedModelForm):
class Meta(ExcludedModelForm.Meta):
model = ExampleModel