customized dropdown value based on foreign key in django admin - django

My Models
class ServicesMenu(models.Model):
category = models.CharField(max_length=200)
class Varient(models.Model):
category = models.ForeignKey(ServicesMenu, on_delete=models.CASCADE)
varient_Name = models.CharField(max_length=200)
class VarientSubField(models.Model):
select_Varient = models.ForeignKey(Varient, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
so the problem is in VariantSubField, its display something like this.
here some value are similar i cant change them but i need is to display "category" from ServicesMenu with these VariantSubField dropdown fields.

To customize dropdown text, you should implement the standard _ _ str _ _ method in the relevant model:
class VarientSubField(models.Model):
select_Varient = models.ForeignKey(Varient, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
def __str__(self):
return self.select_Varient.category + " - " + self.select_Varient.varient_name + " - " + self.name

Related

How do I customise the display text of a related object in a column in Django Tables2?

I'm using Django Tables 2 to display some information from a list of objects, including a column with a related object.
I'm trying to change the text displayed in the column that shows the related object.
My objects are:
Job
class Job(StatusModel):
'''
Model for jobs
'''
STATUS = statuses.JOB_STATUS
start_time = models.DateTimeField(_('time'), default=timezone.now)
pickup_address = models.TextField()
...
destination_address = models.TextField()
...
drivers = models.ManyToManyField(
'Drivers.Driver',
blank=True,
)
...
class Meta:
verbose_name = _('job')
verbose_name_plural = _('jobs')
ordering = ('start_time',)
def __str__(self):
return self.start_time.strftime('%d/%m/%y %H:%M') + ' from ' + self.pickup_address
def get_absolute_url(self):
return reverse('job_view', args=[str(self.id)])
...
Driver
class Driver(StatusModel):
...
current_job = models.ForeignKey(
Job,
on_delete=models.CASCADE,
blank=True,
null=True,
verbose_name=_('Current Job'),
related_name='current_job'
)
...
def __str__(self):
return self.user.get_full_name()
...
My table:
class DriverStatusListTable(tables.Table):
user = tables.Column(linkify=True, verbose_name=_('Driver'))
...
current_job = tables.Column(linkify=True)
class Meta:
model = Driver
...
I want the "current_job" column to show text different to the returned __str__ representation of the Job object - namely:
Job.start_time.strftime('%H:%M') + ' to ' + Job.destination_address,
but I can't work out how to do this, without changing the __str__ method on the Job object.
Any ideas?
Write a Table.render_foo to customize the value output.
Example:
class DriverStatusListTable(tables.Table):
user = tables.Column(linkify=True, verbose_name=_('Driver'))
current_job = tables.Column(linkify=True)
class Meta:
model = Driver
def render_current_job(self, value):
return "Use 'value' parameter here and return useful resposne"

Django : Primary Key is getting null value

Consider the following model :
from django.db import models
class Album(models.Model):
id = models.IntegerField(primary_key=True,null=False)
artist = models.CharField(max_length=200)
album_title = models.CharField(max_length = 250)
genre = models.CharField(max_length=100)
album_logo = models.CharField(max_length = 200)
def __str__(self):
return "id = " + str(self.id) + " artist = " + self.artist + " album = " + self.album_title + " genre = " + self.genre
class Song(models.Model):
id = models.IntegerField(primary_key=True)
album = models.ForeignKey(Album,on_delete=models.CASCADE)
file_type = models.CharField(max_length = 200)
song_title = models.CharField(max_length = 200)
def __str__(self):
return "id = " + str(self.id) + "album = " + self.album.album_title + "song = " + self.song_title
When i am inserting a row in either Album or Song using positional parameters and not giving, django is providing NULL to that particular row. Why so?
First of all, there is no need of explicitly declaring a field named 'id' as Django already creates an id field with every model by default and auto-increments it.
In any case, if you want to deliberately declare a primary key it is recommended do it in the following manner:
id = models.AutoField(primary_key=True)
This is an auto-incrementing primary key.
Reference Official Django Docs:
https://docs.djangoproject.com/en/1.11/topics/db/models/#automatic-primary-key-fields

QuerySet in Django - returns exception

I am trying to understand how exactly query works on Django, i followed the tutorials it´s not working I am not sure what i am doing wrong.
When I run
BeneficientePagar.objects.filter(nome__contains="Joao Pedro")
it returns
"Choices are %s" %s (name, ",".join(available))) django.core.exceptions.FieldError: Cannot resolve keyword "nome into field. Choices are: ID, beneficiente, beneficiente_id,join, join_id, moeda
from django.db import models
# Create your models here.
class Moeda(models.Model):
moeda_ficticia = models.FloatField()
class Join(models.Model):
nome = models.CharField(max_length=150)
nascimento = models.DateField()
cpf = models.IntegerField(primary_key=True)
endereco = models.CharField(max_length=150)
email = models.EmailField()
def __str__(self):
return self.nome
class Beneficiente(models.Model):
ID = models.AutoField(primary_key=True)
nome = models.CharField(max_length=150)
CNPJ = models.IntegerField(max_length = 10)
def __str__(self):
return self.nome
class Favores(models.Model):
ID = models.AutoField(primary_key=True)
favor = models.CharField(max_length=150)
dataInserido = models.DateField()
usuarios = models.ForeignKey(Join)
def __str__(self):
return self.favor
class BeneficientePagar(models.Model):
ID = models.AutoField(primary_key=True)
moeda = models.IntegerField()
beneficiente = models.ForeignKey(Beneficiente)
join = models.ForeignKey(Join)
def __str__(self):
return self.ID
Thanks in advance
If using BeneficientPager, you need to do
BeneficientePagar.objects.filter(beneficient__nome__contains="Joao Pedro")
You are getting the error because nome is a field on Beneficiente, not BeneficientePagar.
You can either do
Beneficiente.objects.filter(nome__contains="Joao Pedro")
which will return a queryset of Beneficientes. Or if you need BeneficientePagar you can query through the foreign key.
BeneficientePagar.objects.filter(beneficiente__nome__contains="Joao Pedro")

Exclude entire QuerySet from results

I have the following models:
class LibraryEntry(models.Model):
player = models.ForeignKey(Player)
player_lib_song_id = models.IntegerField()
title = models.CharField(max_length=200)
artist = models.CharField(max_length=200)
album = models.CharField(max_length=200)
track = models.IntegerField()
genre = models.CharField(max_length=50)
duration = models.IntegerField()
is_deleted = models.BooleanField(default=False)
class Meta:
unique_together = ("player", "player_lib_song_id")
def __unicode__(self):
return "Library Entry " + str(self.player_lib_song_id) + ": " + self.title
class BannedSong(models.Model):
lib_entry = models.ForeignKey(LibraryEntry)
def __unicode__(self):
return "Banned Library Entry " + str(self.lib_entry.title)
I'd like to do a query like this:
banned_songs = BannedSong.objects.filter(lib_entry__player=activePlayer)
available_songs = LibraryEntry.objects.filter(player=activePlayer).exclude(banned_songs)
Basically if a song is banned, I want to exclude it from my set of available songs. Is there a way to do this in Django?
banned_song_ids = (BannedSong.objects.filter(lib_entry__player=activePlayer)
.values_list('lib_entry', flat=True))
available_songs = (LibraryEntry.objects.filter(player=activePlayer)
.exclude('id__in' = banned_song_ids))
The alternative is:
available_songs = (LibraryEntry.objects.filter(player=activePlayer)
.filter(bannedsong__isnull = True))

Django: Model Validation Error ManytoManyField

I get this error while running syncdb
Can't seem to figure out the issue. Please help.
Error: One or more models did not validate:
store.business: Reverse query name for field 'logo' clashes with field 'ImageBank.business'. Add a related_name argument to the definition for 'logo'.
Here are my models:
class Business(models.Model):
business_type = models.ManyToManyField(BusinessType)
business_service_type = models.ManyToManyField(ServiceType)
establishment_type = models.ForeignKey(EstablishmentType)
logo = models.ForeignKey(ImageBank, related_name = '%(class)s_logocreated',)
phone = PhoneNumberField()
address = models.ForeignKey(Address)
website = models.URLField()
name = models.CharField(max_length=64)
def __unicode__(self):
return self.name
class ImageBank(models.Model):
business = models.ForeignKey('Business', related_name='%(class)s_business')
image = models.ImageField(upload_to="images/bank")
def url(self):
return self.image.url
def __unicode__(self):
return unicode(self.business) + " : " + unicode(self.image)
Store Model:
class Store(models.Model):
business = models.ForeignKey(Business,null=True, related_name='business_creator_set')
condition = models.CharField(verbose_name='What do customers have to do?',max_length = 50)
reward = models.CharField(verbose_name='What do customers win?',max_length = 50)
display = models.BooleanField(default=True)
date_created = models.DateTimeField(default=datetime.now)
def __unicode__(self):
return self.condition + ", " + self.reward
Try doing something like this:
...
class ImageBank(models.Model):
business = models.ForeignKey('Business', related_name='%(class)s_business')
....
Also, if that doesn't work, try changing the related_name on the Business.logo field to something not logo_id. logo_id is what the database uses for the field and it may be having a conflict.