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
Related
models.py
from django.db import models
from django.contrib.auth.models import User
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class BlogModel(models.Model):
id = models.AutoField(primary_key=True)
blog_title = models.CharField(max_length=200)
blog = models.TextField()
status = models.IntegerField(choices=STATUS, default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_at']
def __str__(self):
return f"Blog: {self.blog_title}"
class CommentModel(models.Model):
your_name = models.CharField(max_length=20)
comment_text = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
blog = models.ForeignKey('BlogModel', on_delete=models.CASCADE)
class Meta:
ordering = ['-created_at']
def __str__(self):
return f"Comment by Name: {self.your_name}"
admin.py
from django.contrib import admin
from blog.models import BlogModel,CommentModel
class PostAdmin(admin.ModelAdmin):
list_display = ('blog_title', 'status','created_at','updated_at')
list_filter = ('status',)
search_fields = ('blog_title', 'content',)
admin.site.register(BlogModel, PostAdmin)
admin.site.register(CommentModel)
I created a simple blog post website with comments and I want to create reports and on the admin panel I have to see how to achieve this.
Like how many posts are created and how many have comments and how many post are draft and published
I checked this module but I don't understand how to implement it https://pypi.org/project/django-reports-admin/
You already have most of this, by using PostAdmin. The list_display already shows you how many posts are published/draft, and the change list has filters for that as well.
To show the comment count, simply add that to list_display:
class PostAdmin(admin.ModelAdmin):
list_display = ('blog_title', 'status', 'comment_count', 'created_at', 'updated_at')
def comment_count(self, obj):
return obj.commentmodel_set.count()
comment_count.short_description = 'Comment count'
This thus defines a custom method on the PostAdmin, that displays the comment count as a column, and gives it a user-friendly name as column header.
You can expand this with more statistics if you like. The Django admin is highly customizable.
Note: model names should be in CamelCase, so BlogModel and CommentModel should be Blog and Comment respectively.
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 tried to make search field to search by author in the admin panel but i got an error
Related Field got invalid lookup: icontains
i follow the documentation and other stackoverflow question but it doesn't work
#model.py
from django.contrib.auth import get_user_model
User = get_user_model()
class Author(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
return str(self.user)
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=256)
content = models.TextField(verbose_name='content')
date_published = models.DateTimeField(auto_now_add=True)
date_edited = models.DateTimeField(auto_now=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
thumbnail = models.ImageField(blank=True)
def __str__(self):
return self.title
#admin.py
from django.contrib import admin
from .models import Post, Author,
class PostAdmin(admin.ModelAdmin):
list_display = ['title',
'date_published',
'date_edited',
'author', ]
search_fields = ['title',
'author__user',]
admin.site.register(Post, PostAdmin)
admin.site.register(Author)
it works when i changed the search_field[1] to author__id, but since it only accept id, it can't get the username. any idea how to solve it? should i make custom user model?
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
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 :)