Django
related_name
Muss zwingend in ein Model rein, wenn es mehrere FKs aus dem gleichen Foreign Model hat. https://stackoverflow.com/questions/2642613/what-is-related-name-used-for
To add to existing answer - related name is a must in case there 2 FKs in the model that point to the same table. For example in case of Bill of material
@with_author
class BOM(models.Model):
name = models.CharField(max_length=200,null=True, blank=True)
description = models.TextField(null=True, blank=True)
tomaterial = models.ForeignKey(Material, related_name = 'tomaterial')
frommaterial = models.ForeignKey(Material, related_name = 'frommaterial')
creation_time = models.DateTimeField(auto_now_add=True, blank=True)
quantity = models.DecimalField(max_digits=19, decimal_places=10)
So when you will have to access this data you only can use related name
bom = material.tomaterial.all().order_by('-creation_time')
It is not working otherwise (at least I was not able to skip the usage of related name in case of 2 FK's to the same table.)
Class Name / Model Name anzeigen
https://stackoverflow.com/questions/3599524/get-class-name-of-django-model
print(Book.__name__)
Custom Widgets zusätzlichen Context / Daten hinzufügen
Weiß nicht genau warum custom Widgets nicht alle Daten gleich sehen können so wie normale Widgets. Im Zweifel einfach die get_context() Methode overriden:
In case of MultiWidget, similarly to @HenryM's answer, one can subclass get_context method and assign values like so:
def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs)
context["some_field"] = "some_value"
return context
Which in template can be accessed by {{ some_field }}
https://stackoverflow.com/questions/56771884/how-to-add-additional-context-to-a-django-form-widget