admin panel, show date_created and date_updated? - django

I tried following an answer at this previous post:
DateTimeField doesn't show in admin system
But maybe I'm just too dim to understand it.
No field of created_at shows up. Could anyone point me in the right direction?
model
class holding_transaction(models.Model):
holdingname = models.ForeignKey(holding, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
admin.py
class holding_transactionAdmin(admin.ModelAdmin):
readonly_fields = ('created_at', )
admin.site.register(holding_transaction, holding_transactionAdmin)
Edit:

Update:
Here is the code that worked for me for an imaginary application called Beatles:
beatles/models.py:
from django.db import models
# Create your models here.
class Person(models.Model):
name = models.CharField(max_length=128)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self): # __unicode__ on Python 2
return self.name
beatles/admin.py
from django.contrib import admin
# Register your models here.
from beatles.models import Person
#admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
readonly_fields = ('created_at', )
The answer to the question mentioned, states that this is not possible to happen.
Nonetheless, if you want to edit such fields, according to the docs you proceed as follows:
If you want to be able to modify this field, set the following instead
of auto_now_add=True:
For DateField: default=date.today - from datetime.date.today()
For DateTimeField: default=timezone.now - from django.utils.timezone.now()
If you want those fields just to be displayed, you can use the following code:
class YourModelAdmin(admin.ModelAdmin):
readonly_fields = ('created_at', 'updated_at', )
admin.site.register(YourModel, YourModelAdmin)

Related

Retrieve field values to Django Admin using many to many relationships

I have a simple task: I need to expose player name related to Game in game list (Django Admin). Game object has ManyToMany relationship with Player object via 'players' attribute. The problem is that now I have empty 'players_list' field (empty list means I don't know what to do and just leave it here[enter image description here][1]), though I tried Player.objects.all() and obviously got all players even those who are not bound to particular game.
I feel it has simple solution but my brain refuses to work after 55 opened tabs.
Thanks in advance!
This is my models.py
from django.db import model
class Player(models.Model):
name = models.CharField(max_length=54, default="")
email = models.EmailField(max_length=54)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Game(models.Model):
name = models.CharField(max_length=254, default="")
players = models.ManyToManyField(Player, blank=True, related_name='player_games')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
players_list = []
def __str__(self):
return self.name
and admin.py
from django.contrib import admin
from .models import Game, Player
class PlayerInline(admin.TabularInline):
model = Game.players.through
#admin.register(Player)
class Admin(admin.ModelAdmin):
search_fields = ['name', 'email']
list_display = ('name', 'email', 'created_at', 'updated_at')
inlines = [
PlayerInline,
]
#admin.register(Game)
class AdminAdmin(admin.ModelAdmin):
list_display = ('name', 'created_at', 'updated_at', 'players_list')
inlines = [
PlayerInline,
]
exclude = ('players',)
Pic as it looks now
[1]: https://i.stack.imgur.com/KVJ5y.png
The best approach here will be creating custom method in your model instead of single variable. You will not even have to change your list_display:
class Game(models.Model):
...
def players_list(self):
return self.players.all()
Alternatively, if you want only names of players or anything else from, you can change it (or add another method) to something like that:
class Game(models.Model):
...
def players_list(self):
return [player for player in self.players.all()]
# or
return [player.name for player in self.players.all()]
This is called list comprehension, if you are not familiar with it.

How to add parameters to ManyToManyField Django

Question:
Models.py
Suggest i have got djanog class A:
class A(models.Model):
slug = models.SlugField(max_length=200, blank=True)
code = models.CharField("A", max_length=250)
name = models.CharField(("A"), max_length=250)
body = RichTextField(("A"), max_length=2500, blank=True, null=True)
policy = models.CharField(("A"), max_length=25, blank=True, null=True)
and i create class B:
class B(models.Model):
block = models.ManyToManyField(A)
In Admin portal, when creating an instance of class B, django chooses the ManyToMany field automatically to search based on name. I would like to add the fields based on the code of class A. Help please, I can't get it to work.
Thanks in advance for the tips!
Edit:
Admin.py
from django.contrib import admin
from import_export.admin import ImportExportMixin
from .models import A, B
admin.site.register(B)
class AAdmin(ImportExportMixin, admin.ModelAdmin):
list_display = ['code', 'name',]
search_fields = ['code', 'name', 'body']
admin.site.register(A, AAdmin)
Just figured it out by using raw_id_fields in admin.py :)

Exporting a field from another model, using foreign key

I've just set up the whole import-export thing and I just can't make it export a field from another model, using the foreign key.
models.py
from django.db import models
from django.contrib.auth.models import User
from datetime import date
from .validators import validate_file_size
# Create your models here.
class CORMeserii(models.Model):
CodCOR = models.CharField(max_length=25, primary_key=True, unique=True)
MeserieCor = models.CharField(max_length=50, unique=True)
def __str__(self):
return str(self.CodCOR + " - " + self.MeserieCor)
class Meta:
verbose_name_plural = "CORuri"
class Oferta(models.Model):
solicitant = models.ForeignKey(User, on_delete=models.CASCADE)
cor = models.ForeignKey(CORMeserii, on_delete=models.CASCADE)
dataSolicitare = models.DateField(default=date.today)
locuri = models.IntegerField()
agentEconomic = models.CharField(max_length=50)
adresa = models.CharField(max_length=150)
dataExpirare = models.DateField()
experientaSolicitata = models.CharField(max_length=200)
studiiSolicitate = models.CharField(max_length=200)
judet = models.CharField(max_length=20)
localitate = models.CharField(max_length=25)
telefon = models.CharField(max_length=12)
emailContact = models.EmailField(max_length=40)
rezolvata = models.BooleanField(default=False)
def __str__(self):
return str(self.cor)
admin.py
from django.contrib import admin
from .models import Oferta, CORMeserii
from import_export import resources
from import_export.admin import ImportExportMixin, ImportExportModelAdmin
import tablib
# Register your models here.
class CorImEx(resources.ModelResource):
class Meta:
model = CORMeserii
class CorAdmin(ImportExportMixin, admin.ModelAdmin):
list_display = ('CodCOR', 'MeserieCor')
resource_class = CorImEx
class CorImExAdmin(ImportExportModelAdmin):
resource_class = CorImEx
class OferteImEx(resources.ModelResource):
class Meta:
model = Oferta
fields = ('id', 'solicitant', 'cor', 'oferta.cor.MeserieCor')
class OfertaAdmin(ImportExportMixin, admin.ModelAdmin):
list_display = ('id', 'solicitant', 'dataExpirare', 'dataSolicitare')
resource_class = OferteImEx
class OferteImExAdmin(ImportExportModelAdmin):
resource_class = OferteImEx
admin.site.register(Oferta, OfertaAdmin)
admin.site.register(CORMeserii, CorAdmin)
You can see it in the OferteImEx class - the field 'oferta.cor.MeserieCor'.
I want to export the MeserieCor field from the model CORMeserii - but I can't figure it out.
I tried with: 'oferta.cor.MeserieCor',
cor.MeserieCor', 'MeserieCor' (even though the last 2 ones don't make sense to me at all).
Is there any way to export that field somehow, even though it is from another model? (I'm pretty sure there is but I can't figure it out)
Thanks.
In Django you use double underscore (__) to follow relationship in lookups. It's in the documentation:
Django offers a powerful and intuitive way to “follow” relationships in lookups, taking care of the SQL JOINs for you automatically, behind the scenes. To span a relationship, just use the field name of related fields across models, separated by double underscores, until you get to the field you want.
Link: Lookups that span relationship
There is even an example in the django import export documentation how to follow relationship:
When defining ModelResource fields it is possible to follow model relationships:
class BookResource(resources.ModelResource):
class Meta:
model = Book
fields = ('author__name',)
Source: https://django-import-export.readthedocs.io/en/latest/getting_started.html#customize-resource-options

django models CharField

I am trying to create a django slideshow app using some existing code and adding some new. I am unsure if what I am doing is correct, I think the problem is in my models.py and as a python beginner I think I need some advice.
models.py
from django.db import models
import datetime
class Slider(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(blank=True)
slideshow = models.ForeignKey('Slideshow')
images = models.ImageField(upload_to='slideshow', max_length=1000, blank=True, null=True)
def __unicode__ (self):
return self.title
class Slideshow(models.model):
name = models.CharField(max_length=50)
touchEnabled = models.BooleanField(blank=True, default=False)
speed = models.IntegerField(blank=True, default=500)
class wrapperClass_options(models.Model):
choices = (('mydiv'))
wrapperClass = models.CharField(blank=True, max_length=20, default=choices)
# div class to wrap the slider in. Change it to prevent using default styles.
pub_date = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name
I am pretty sure that my BooleanField and IntegerField are ok, but am not so sure about the CharField.
the charfield default is #mydiv but it needs to be able to be changed to whatever a developer needs it to be, am I doing the right thing by creating wrapperclass_options and adding the default to it choices = 'mydiv' or should I be doing something different altogether?
Below is my admin.py
admin.py
from satchmo_slideshow.models import Slider, Slideshow
from django.contrib import admin
class SlideInline(admin.StackedInline):
model = Slider
class SlideshowAdmin(admin.ModelAdmin):
fieldsets = [(title, {'fields': ['name']}),
('speed', {'fields': ['Default: 500ms']}),
('wrapperClass', {'fields': ['Default: mydiv']}),
('touchEnabled', {'fields': ['Default: False']}),
]
inlines = [SlideInline]
list_display = ['name', 'pub_date']
list_filter = ['pub_date']
search_fields = ['name']
admin.site.register(Slideshow, SlideshowAdmin)
using python 2.7 and django 1.4.2

django ForeignKey model filter in admin-area?

Hi I need really very very simple example. First my models:
#This my student models
from django.db import models
SEX_CHOICES= (
('M', 'Male'),
('F', 'Female'),
)
class Students(models.Model):
student_name = models.CharField(max_length=50)
student_sex = models.CharField(max_length=8, choices=SEX_CHOICES)
student_city = models.Charfield(max_length=50)
student_bio = models.TextField()
def __unicode__(self):
return self.student_name
O.K. Let see my Classes Model.
#This my Classes models
from django.db import models
from myproject.students.models import *
class Classes(models.Model):
class_number= models.CharField(max_length=50)
class_student_cities = models.ForeignKey(Students)
class_year = models.DateField()
def __unicode__(self):
return self.class_number
My classes/admin.py file looks like that:
from myproject.classes.models import *
from myproject.students.models import *
from django.contrib import admin
class ClassesChoiceField(Students):
class_student_cities = Classes.objects.get(id=1).class_student_cities.student_city
admin.site.register(Classes)
I get this error:
DoesNotExist at /admin/classes/classes/add/
Classes matching query does not exist.
How can i show in the class_student_cities area the Students.student_city datas? I guess that about django-admin area.
When i do it with ForeignKey(Students) i just see in that area the Students.student_name data :S. I'm really wondering how can I do it? Can you give me a little example?
Many Thanks!
See the documentation.
To get student_city from queryset, you can use:
Classes.objects.get(id=1).class_student_cities.student_city
And if you want to relate your foreignkey field not to primary key, you should use to_field argument
https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.to_field
It will be like:
class_student_cities = models.ForeignKey(Students, to_field='student_city')
There are a few problems -- basically things are 'not quite right', which is why you keep being referred to the docs.
Here is an example of what an admin.py should look like:
from django.contrib import admin
from articles.models import Article
def show_articletype_thumbnail(self):
return self.image.admin_thumbnail()
show_articletype_thumbnail.allow_tags=True
show_articletype_thumbnail.short_description = 'Image'
class ArticleAdmin(admin.ModelAdmin):
save_on_top = True
list_display = ['status', 'articletype', 'issue', 'penname', 'issue', show_articletype_thumbnail]
list_display_links = ['articletype']
list_filter = ['articletype', 'allow_comments', 'template', 'issue']
admin.site.register(Article, ArticleAdmin)