I have created a new model for my app Consumptions but it doesn't show up.
I know that I have to put it on the admin.py page but still not working.
I don't know what could be happening
This is my models.py page:
from logs.mixins import LogsMixin
# Other models
class MF(LogsMixin, models.Model):
"""Definición del modelo de Proveedor."""
name = models.CharField("Nombre", null=False, default="MF", max_length=50)
class Meta:
verbose_name = 'Módulo formativo'
verbose_name_plural = 'Módulos formativos'
def __str__(self):
return self.name
# Other models
And this is my admin.py page:
from django.contrib import admin
from .models import Provider, Consumption, Message, Course, Call, Platform, MF
admin.site.register(Provider)
admin.site.register(Consumption)
admin.site.register(Message)
admin.site.register(Course)
admin.site.register(Call)
admin.site.register(Platform)
admin.site.register(MF)
As you can see is not my only model, I do the same with all of them but the MF one is not showing up on the admin page.
What am I doing wrong?
Try following approach:
class ProviderAdmin(admin.ModelAdmin):
model = Provider
admin.site.register(Provider, ProviderAdmin)
In ProviderAdmin class you may specify filters, search fields or empty value handling:
search_fields = ('',)
list_filter = ('',)
empty_value_display = 'empty'
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
In my django app I want to set focus to the first CharField (task) when the page loads.
my models.py is
from django.db import models
class ListModel(models.Model):
task = models.CharField(max_length=255)
status = models.BooleanField(default=False)
def __str__(self):
return f"{self.task} : {str(self.status)}"
and forms.py is
from django.forms import ModelForm
from .models import ListModel
class ListForm(ModelForm):
class Meta:
model = ListModel
fields = ["task", "status"]
I have tried adding the following widget in my CharField (in models.py):
task = models.CharField(max_length=255, widget=models.TextInput(attrs={'autofocus': True})
but it gives an AttributeError: module 'django.db.models' has no attribute 'TextInput'
I have also tried adding the following to the ListForm class (in forms.py):
def __init__(self):
self.fields['task'].widget.attrs.update(autofocus = 'autofocus')
though I am not getting any error for this, but when I load my page the focus is not set to the task CharField either. What can I do add auto-focus to my CharField?
You are confusing model fields (which are used to store data in the database), and form fields, which are used to obtain, validate and clean data the user has entered.
You thus work with:
from django.forms import ModelForm
from django import forms
from .models import ListModel
class ListForm(ModelForm):
# forms ↓
task = forms.CharField(
max_length=255,
# forms ↓
widget=forms.TextInput(attrs={'autofocus': True})
)
class Meta:
model = ListModel
fields = ['task', 'status']
I'm trying to hide and delete two fields from showing in a form I created in the Django administration page using ModelForm.
I looked at answers that said I should use the "exclude" meta field, but I don't know why it's not working in my case.
Here is my code:
models.py:
class Activity(models.Model):
type = models.CharField(max_length=50, default="")
title = models.CharField(max_length=200, default="")
description = models.CharField(max_length=500)
owner = models.ForeignKey(User, related_name="owner")
college = models.CharField(max_length=200)
location = models.CharField(max_length=200)
room = models.CharField(max_length=200)
startDate = models.DateTimeField(null=True, blank=True)
endDate = models.DateTimeField(null=True, blank=True)
attendee = models.ManyToManyField(Attendee, related_name="attendees",null=True, blank=True)
volunteer = models.ManyToManyField(Volunteer, related_name="volunteers",null=True, blank=True)
I'm trying to exclude the "attendee & volunteer" fields from displaying in the Django administration form.
In admin.py I have:
from django.contrib import admin
from django import forms
from KSUvity.models import Activity
class ActivityForm(forms.ModelForm):
class Meta:
model = Activity
exclude = ['attendee', 'volunteer',]
class ActivityAdmin(admin.ModelAdmin):
exclude = ['attendee', 'volunteer',]
form = ActivityForm
admin.site.register(Activity, ActivityAdmin)
You have to create an admin.py file in your app and register your models
Follow the instuctions
See the example below
from django import forms
from django.contrib import admin
from myapp.models import Person
class PersonForm(forms.ModelForm):
class Meta:
model = Person
exclude = ['name']
class PersonAdmin(admin.ModelAdmin):
exclude = ['age']
form = PersonForm
admin.site.register(Person, PersonAdmin)
You can use either fields or exclude in one class.
In your app admin field add this code.
app_name/admin.py
from django.contrib import admin
class ActivityAdmin(admin.ModelAdmin):
exclude = ('attendee', 'volunteer',)
You have to use ModelAdmin option to exclude fields from form in Django administration, either ModelAdmin.exclude or ModelAdmin.fields. Below is an example:
class ActivityAdmin(admin.ModelAdmin):
exclude = ('attendee', 'volunteer', )
To make it work, you register model like this:
admin.site.register(Activity, ActivityAdmin)
You add this code to admin.py file.
Say I have this app named Pantry that is to connect to any other app I may come along. To keep the app decoupled, generic relations are used through the model LinkedItem which connects the Ingredients model to apps outside Pantry.
I can make a filter_horizontal show up for the LinkedItem's admin in Django. Now I would like the content on the other end of the generic relation, say an app named Bakery, to be able to do a filter_horizontal with ingredients.
Pantry
models.py
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import fields
class Ingredient(models.Model):
'''
Model containing all the ingredients, their slugs, and their descriptions
'''
name = models.CharField(unique=True, max_length=100)
slug = models.SlugField(unique=True, max_length=100)
description = models.CharField(max_length=300)
# method to return the name of the db entry
def __str__(self):
return self.name
class LinkedItem(models.Model):
'''
Model that links ingredients to various other content models
'''
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = fields.GenericForeignKey('content_type', 'object_id')
ingredient = models.ManyToManyField(Ingredient)
# method to return the name of the db entry
def __str__(self):
return self.ingredient.name
# defines options for the model itself
class Meta:
unique_together = (('content_type','object_id')) # prevents duplicates
Bakery
admin.py
from django.contrib import admin
from bakery.models import Cake
class CakeAdmin(admin.ModelAdmin):
filter_horizontal = ('') # what to put here so ingredients show up?
Any ideas?
A solution is to create a GenericTabularInline for LinkedItem and putting some restrictions on the display to avoid duplicates like below:
from django.contrib.contenttypes.admin import GenericTabularInline
class LinkedItemAdmin(GenericTabularInline):
model = LinkedItem
# choosing the field and display
field = ['ingredient']
filter_horizontal = ['ingredient']
# These help with removing some potential issues in the admin
extra = 0
min_num = 1
max_num = 1
can_delete = False
Then in the CakeAdmin I can do this to make the ingredients show up.
class CakeAdmin(admin.ModelAdmin):
inlines = [LinkedItemAdmin]
So here is the code that I am working with right now
models.py
from django.db import models
class Building(models.Model):
name = models.TextField(max_length=60)
def __str__(self):
return self.name
class Charge(models.Model):
item = models.CharField(max_length=60)
cost = models.CharField(max_length=15)
last_updated = models.DateField(default='',auto_now=True)
buildings = models.ManyToManyField(Building)
def __str__(self):
return self.item
admin.py
from django.contrib import admin
from rlscharges.models import Charge, Building
from django.db import models
from django.forms import CheckboxSelectMultiple
class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.ManyToManyField: {'widget': CheckboxSelectMultiple},
}
class BuildingInline(admin.TabularInline):
model = Charges.building.through
class BuildingAdmin(MyModelAdmin):
fields = ['name']
inlines = [BuildingInline]
admin.site.register(Charge, MyModelAdmin)
admin.site.register(Building, BuildingAdmin)
I basically just want the checkboxselectmultiple to show up on the Charge and Building models admin pages. Right now the checkbox only shows up on the Charge model and the TabularInline shows up on the Building model. Is there a way to get formfield_overrides to apply to the BuildingInline so it shows the checkboxes and not the TabularInline? Or do I need to do something to the relationship of the models? I apologize ahead of time if this is a stupid question, I am just getting started with django.