I have two models:
class ModelA(models.Model):
id = models.AutoField()
name = models.ManyToManyField(ModelB)
class ModelB(models.Model):
id = models.AutoField()
In the Django Admin page, I noticed that I now see a table called "modelA-modelB relationships". Is this the expected outcome?
If so, how can I rename this to be something more user-friendly? I've tried several parameters verbose_name, related_name, and db_table for the ManytoManyField and none seem to overwrite the default name.
Related
I have these two models :
class Project(models.Model):
name = models.CharField(max_length=50)
users = models.ManyToManyField(User)
class User(models.Model):
name = models.CharField(max_length=25)
I want to get a queryset containing all the Projects with a specific user in the 'users' ManyToManyField
I tried this : Project.objects.filter(users__contains=user), but it's not working
Does someone know how can I do it ?
if filtering with id:
Project.objects.filter(users=search_id)
if filtering with user name:
Project.objects.filter(users__name__icontains=search_input)
I am displaying data in Django admin panel for many to many relationship tables. I got None instead of a list of names.
I am using:
Python: 3.6
Django: 2.2
List_display for ManytoMany fields in Admin panel
I had also already asked a related question on this topic. That being said I changed my model since then (I also got not answers).
models:
class Assessment(models.Model):
name = models.CharField(max_length=255)
class Participant(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
first_name = models.CharField(max_length=255,blank=True,null=True)
class Seminar(models.Model):
topic = models.CharField(max_length=255)
assessment = models.ManyToManyField(Assessment,blank=True)
participant = models.ManyToManyField(Participant,blank=True,through='SeminarParticipant',through_fields=('seminar','participant'))
class SeminarParticipant(models.Model):
seminar = models.ForeignKey(Seminar,blank=True,on_delete=models.CASCADE)
participant = models.ForeignKey(Participant,blank=True,on_delete=models.CASCADE)
request_time = models.PositiveIntegerField(default=0,validators=[MinValueValidator(0),])
is_survey_completed = models.BooleanField(default=False)
admin:
#admin.register(Seminar)
class SeminarAdmin(admin.ModelAdmin):
list_display = ('topic''assessment')
def assessment(self,obj):
return "\n".join([item for item in obj.assessment.all()])
I was expecting name of assessment in list_display of seminar admin but got assessments.Assessment.None in list_display of admin panel.
Snapshot of output:
Thank you very much for your help
assessment is the name of the field, which will be found before your method. Call the method something else and use that name in list_display.
class SeminarAdmin(admin.ModelAdmin):
list_display = ('topic', 'assessment_list')
def assessment_list(self, obj):
return "\n".join([item for item in obj.assessment.all()])
(Although note, assessment is an odd name for a field that contains many assessments; you should think about renaming the field itself.)
I am creating my own users, Restaurant and Customer. I have extended the AbstractUser class and then created a OneToOneField field for each user. I am wondering if I need to add the AUTH_USER_MODEL in my settings.py. And also wondering what that does exactly...
What I was planning on doing was adding to my settings.py:
AUTH_USER_MODEL = 'myapp.Customer','myapp.Restaurant'
Do I have the right idea here?
My models.py:
class User(AbstractUser):
is_restaurant = models.BooleanField(default=False)
is_customer = models.BooleanField(default=False)
class Restaurant(models.Model):
user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)
restaurant_name = models.CharField(max_length=50)
def __str__(self):
return self.restaurant_name
class Customer(models.Model):
user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)
address = models.CharField(max_length=200)
def __str__(self):
return self.user.get_full_name()
No. AUTH_USER_MODEL isn't expecting a tuple, so this won't work.
In any case, Restaurant and Customer are not your user model; your subclassed User is. That's what you should be putting in that setting.
I would suggest create single user table instead of three different tables and add type as restaurant, customer, admin etc. And add only one table into settings file. this won't lead any further issues authentication etc. Having single user table is always robust. In your case having three tables seems not good to maintain.
========== UPDATE ===========
Create model for user named as CustomUser (or name which you feel better) and extends to User Model of Django using AbstractBaseUser,PermissionsMixin. like
class CustomUser(AbstractBaseUser): have all fields which user table has already. and add your desired table to bifurcate type of restaurant and
customer have type field with choices option.
For further help you can check section https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#substituting-a-custom-user-model
I have simply model class:
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
I want to set attribute title unmodifiable in django admin. What should I do to set this?
Add the field name to readonly_fields of that model's ModelAdmin class. According to the documentation:
By default the admin shows all fields as editable. Any fields in this option (which should be a list or tuple) will display its data as-is and non-editable.
In your situation this looks like:
readonly_fields = ("title",)
I've got a weird problem in django admin list_display. Whenever I add a foreign key to a list_display the whole change list view goes blank showing only the total no of entries.
models.py:
class Organization(models.Model):
org_id = models.AutoField(primary_key=True)
org_name = models.CharField(max_length=288)
def __unicode__(self):
return self.org_name
class Meta:
db_table = u'organization'
class Server(models.Model):
server_id = models.AutoField(primary_key=True)
server_name = models.CharField(max_length=135,verbose_name="Server Name")
org = models.ForeignKey(Organization,verbose_name="Organization")
def __unicode__(self):
return self.server_name
class Meta:
db_table = u'server'
admin.py:
class ServerAdmin(admin.ModelAdmin):
list_display = ('server_name','org')
admin.site.register(Server,ServerAdmin)
Now I'd expect this code to show me the organization name in the ChangeList View, But instead I get this:
If I remove the org in the list_display of ServerAdmin class, I get this:
I didn't modify the template or override any ModelAdmin methods. I'm using Mysql(5.1.58) as my database that comes with ubuntu 11.10 repository.
I'll be really glad if I could a get a sloution for this problem guys. Thanks in advance.
I second Stefano on the fact that null=True, blank=True is to be added. But, I think you only need to add it to the org_name field of the Organization model. That should make your way through. It has to be done because you have run inspectdb to create models from your legacy DB. And probably the organization table in the DB has an empty string stored. So, adding the above would allow the Admin to have a blank field/column displayed.
Moreover, you can also try using callbacks in situations where you don't want to make changes to your model definition like the above.
Try adding null=True, blank=True to all your model fields.
Usually django admin will silenty fail (thus show no records in the list) if the row does not validate the model constraints.
See: https://stackoverflow.com/a/163968/1104941
Does the following work for you?
admin.py:
class ServerAdmin(admin.ModelAdmin):
list_display = ('server_name','org__org_name')
admin.site.register(Server,ServerAdmin)
I had a similar problem and solved it like this (using your example):
class ServerAdmin(admin.ModelAdmin):
list_display = ('server_name', 'get_org')
def get_org(self, obj):
return obj.org.org_name
get_org.short_description = 'Org'
admin.site.register(Server,ServerAdmin)