How can i remove extra "s" from django admin panel? - python

I am really very much irritated by the extra "s" added after my class name in django admin eg class 'About' in my model.py becomes 'Abouts' in admin section. And i want it not to add extra 's'. Here is my model.py file-
class About(models.Model):
about_desc = models.TextField(max_length=5000)
def __unicode__(self): # __str__ on Python 3
return str(self.about_desc)
Please anybody suggest me how django can solve my problem.

You can add another class called Meta in your model to specify plural display name. For example, if the model's name is Category, the admin displays Categorys, but by adding the Meta class, we can change it to Categories.
I have changed your code to fix the issue:
class About(models.Model):
about_desc = models.TextField(max_length=5000)
def __unicode__(self): # __str__ on Python 3
return str(self.about_desc)
class Meta:
verbose_name_plural = "about"
For more Meta options, refer to https://docs.djangoproject.com/en/1.8/ref/models/options/

Take a look at the Model Meta in the django documentation.
Within a Model you can add class Meta this allows additional options for your model which handles things like singular and plural naming.
This can be used in the following way (in english we do not have sheeps) so verbose_name_plural can be used to override djangos attempt at pluralising words:
class Sheep(model.Model):
class Meta:
verbose_name_plural = 'Sheep'

inside model.py or inside your customized model file add class meta within a Model Class.
If not mentioned then a extra 's' will be added at the end of Model Class Name which will be visible in Django Admin Page.
class TestRoles(model.Model):
class Meta: verbose_name_plural = 'TestRoles'

Related

Multiple Django Admin Arguments with Extensions

Is there a way to use multiple Django extensions in the admin.site.register() inside admin.py? I'm using "simple-history" and "import-export" extensions, but I can only have one of them in the admin.site.register().
Example: I have a model named, "Cars", that is using the "simple-history" extension so I need admin.site.register(Cars, SimpleHistoryAdmin), as their documentation says it should. I want to use the import/export extension as well to the same "Cars" model, but the admin.site.register() doesn't take multiple arguments for me to add it.
models.py
class Cars(models.Model):
Year = models.CharField(max_length=30)
Make = models.CharField(max_length=30)
Model = models.CharField(max_length=30)
history = HistoricalRecords()
class Meta:
verbose_name_plural = "Car Table"
def __str__(self):
return self.Make
admin.py
class CarResource(resources.ModelResource):
class Meta:
model = Cars
fields = ('id','Year', 'Make', 'Model',)
class CarAdmin(ImportExportModelAdmin):
resource_class = CarResource
pass
#I want to use the import/export extension (code above), along with simple-history
admin.site.register(Cars, CarAdmin)
admin.site.register(Cars, SimpleHistoryAdmin)
I've tried using a proxy and inlines, but the proxy makes a new model which I don't want and when using inlines I get an error saying that it requires a foreign key, but I'm not trying to get the model objects from a different model. Naming them the same model doesn't work because the model is already registered. Any help is much appreciated!
In python, class can have more than one parent. Just inherit from 2 parents at once. But both ImportExportModelAdmin and SimpleHistoryAdmin are inheriting from ModelAdmin, that's not good. There is also ImportExportMixin, we can use it instead of ImportExportModelAdmin, so there will be only one reference to ModelAdmin.
class CarResource(resources.ModelResource):
class Meta:
model = Cars
fields = ('id','Year', 'Make', 'Model',)
class CarAdmin(ImportExportMixin, SimpleHistoryAdmin):
resource_class = CarResource
pass
#I want to use the import/export extension (code above), along with simple-history
admin.site.register(Cars, CarAdmin)

Recursive Inline with Foreign Fields Django Admin

I am trying to open django admin for the following models..
class FirstModel(models.Model):
name = models.CharField(max_length=100)
class SecondModel(models.Model):
name = models.CharField(max_length=100)
firstModel = models.ForeignKey(FirstModel, related_name='secondList')
class ThirdModel(models.Model):
name = models.CharField(max_length=100)
secondModel = models.ForeignKey(SecondModel, related_name='thirdList')
I am trying to create an admin.py for the following models as follows..
class ThirdModelInline(admin.TabularInline):
model = ThirdModel
extra = 1
class SecondModelInline(admin.StackedInline):
model = SecondModel
inlines = [ThirdModelInline]
class FirstModelAdmin(admin.ModelAdmin):
inlines = [SecondModelInline]
admin.site.register(FirstModel, FirstModelAdmin)
I want to be able to edit the SecondModel and ThirdModel as a recursive relation inside FirstModel. But this is not working. I tried to follow this link : [Model with recursive self relation in Django's admin
[1]: Model with recursive self relation in Django's admin. Any help would be appreciated. Thanks!!
Found a very good library after some websearch. Might help someone else..
https://github.com/s-block/django-nested-inline
django-nested-inline isn't (yet?) supported on latest django releases.
But you could consider using django-nested-admin that is almost the same.

Adding help_text in a superclass attribute

Let's say I have a model called MySuper:
class MySuper(models.Model):
some_attr = models.CharField(max_length=128)
And I have two subclasses that inherit from this model, called MySub1 and MySub2.
I need to add a help_text to some_attr, but must be different in each subclass. Is there any way to do this?
class MySub1(MySuper):
# ...
# add help_text='Help text of some_attr inside MySub1'
class MySub2(MySuper):
# ...
# add help_text='Help text of some_attr inside MySub2'
Another way to achieve this without having to fully redefine the field would be:
class MySub1(MySuper):
pass
MySub1._meta.get_field('some_attr').help_text = 'sub1 help text'
class MySub2(MySuper):
pass
MySub2._meta.get_field('some_attr').help_text = 'sub2 help text'
I needed to do this for two identical models that have different image sizes. There's probably some brilliant way to generalise this, but for two items my answer will do fine. First create a file called forms.py in your app.
from django import forms
from .models import FeaturedProduct, ShopProduct
class FeaturedProductForm(forms.ModelForm):
class Meta:
model = FeaturedProduct
ihelp = "Image should be 500x220."
src = forms.ImageField(help_text=ihelp,required=False)
class ShopProductForm(forms.ModelForm):
class Meta:
model = FeaturedProduct
ihelp = "Image should be 100x100."
src = forms.ImageField(help_text=ihelp,required=False)
Note that required defaults to true, even if you have null=True, blank=True on your models. Then in admin.py define your ModelAdmins as follows:
from .forms import FeaturedProductForm, ShopProductForm
class ShopProductAdmin(admin.ModelAdmin):
form = ShopProductForm
class FeaturedProductAdmin(admin.ModelAdmin):
form = FeaturedProductForm
I left out a few imports and the whole admin.site.register nonsense. Let me know if you need any more info. The complete list of forms.FIELDS can be found here:
https://docs.djangoproject.com/en/dev/ref/forms/fields/

Django admin List Display + ForeignKey = Empty Change List

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)

How can I update only certain fields in a Django model form?

I have a model form that I use to update a model.
class Turtle(models.Model):
name = models.CharField(max_length=50, blank=False)
description = models.TextField(blank=True)
class TurtleForm(forms.ModelForm):
class Meta:
model = Turtle
Sometimes I don't need to update the entire model, but only want to update one of the fields. So when I POST the form only has information for the description. When I do that the model never saves because it thinks that the name is being blanked out while my intent is that the name not change and just be used from the model.
turtle_form = TurtleForm(request.POST, instance=object)
if turtle_form.is_valid():
turtle_form.save()
Is there any way to make this happen? Thanks!
Only use specified fields:
class FirstModelForm(forms.ModelForm):
class Meta:
model = TheModel
fields = ('title',)
def clean_title(self....
See http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#controlling-which-fields-are-used-with-fields-and-exclude
It is common to use different ModelForms for a model in different views, when you need different features. So creating another form for the model that uses the same behaviour (say clean_<fieldname> methods etc.) use:
class SecondModelForm(FirstModelForm):
class Meta:
model = TheModel
fields = ('title', 'description')
If you don't want to update a field, remove it from the form via the Meta exclude tuple:
class Meta:
exclude = ('title',)

Categories

Resources