Showing certain fields of related models in Django Admin - django

I have following scenario:
There are Containers.
Each Container has Contents.
There are Consumers.
Each Consumer measures temperature of Contents
I have Django admin page that shows:
Consumer
Container Content
Container Content Temperature
Date when Temperature was measured
I need this page to show also name of 'Parent Container' for 'Container Content'
How can I do it?
Here is content of my models.py and admin.py
in models.py:
class Container_Model(models.Model):
container_name = models.CharField(max_length=200)
def __str__(self):
return unicode(self.container_name)
class Container_Content_Model(models.Model):
container_content_name = models.CharField(max_length=200, )
parent_container = models.ForeignKey(Container_Model,
related_name="parent_container", on_delete=models.CASCADE)
container_content_consumers =
models.ManyToManyField(Container_Consumer_Model)
def __str__(self):
return unicode(self.container_content_name,)
class Container_Consumer_Model(models.Model):
container_consumer_name = models.CharField(max_length=200)
def __str__(self):
return unicode(self.container_consumer_name)
class Container_Content_Temperature_Model(models.Model):
container_content = models.ForeignKey(Container_Content_Model)
container_consumer = models.ForeignKey(Container_Consumer_Model)
container_content_temperature = models.CharField(max_length=64,
blank=True, null=True)
container_content_temperature_measured_at = models.DateField()
def __str__(self):
return unicode(self.container_content_temperature)
in admin.py:
#admin.register(models.Container_Content_Temperature_Model)
class container_content_temperature_model_admin(admin.ModelAdmin):
list_display = (
'container_consumer',
'container_content',
'container_content_temperature',
'container_content_temperature_measured_at',
)

Related

show related fields in django admin panel

I have 3 django models. Requirement Model has its own fields. RequirementImage and RequirementDOc models have Requirement as foreign key in them which are used for multiple image and multiple document upload. In admin ,I want to show the Requirement along with the images and documents related to requirement. How can i show it in admin panel.
i want to show a view where i can list all fields of Requirement and RequirementImages and RequirementDocs together.
Below is the exact code of models.
class Requirement(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length = 5000)
mobile = models.CharField(max_length=15, null=True, blank=True)
email = models.EmailField(null=True, blank=True)
city = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class RequirementImage(models.Model):
requirement = models.ForeignKey('Requirement', on_delete=models.CASCADE)
image = models.ImageField(null=True, blank=True, validators=[
FileMimeValidator()
], upload_to=settings.MEDIA_RELATIVE_ROOT + "requirements/images")
class RequirementDoc(models.Model):
requirement = models.ForeignKey('Requirement', on_delete=models.CASCADE)
requirement_file = models.FileField(null=True, blank=True, upload_to=settings.MEDIA_RELATIVE_ROOT + "requirements/docs")
Python version is 3.7.12 and django version is 3.2.14
in models.py
from django.utils.safestring import mark_safe
class RequirementImage(models.Model):
requirement = models.ForeignKey('Requirement', on_delete=models.CASCADE)
image = models.ImageField(null=True, blank=True, validators=[
FileMimeValidator()
], upload_to=settings.MEDIA_RELATIVE_ROOT + "requirements/images")
def photo_tag(self):
return mark_safe('<img src="/your_path/{0}">'.format(self.image))
photo_tag.short_description = 'Photo of prescription'
photo_tag.allow_tags = True
and when you want to use it in admin
list_display = ('get_photo')
def get_photo(self, obj):
return obj.photo.photo_tag()
get_photo.short_description = 'Photo of prescription'
This is the right answer.we need to use TabularInline.
class RequirementImageInline(admin.TabularInline):
model = RequirementImage
fields = ['image']
extra = 1
class RequirementDocInline(admin.TabularInline):
model = RequirementDoc
fields = ['requirement_file']
extra = 1
class RequirementAdmin(admin.ModelAdmin):
inlines = [RequirementImageInline,RequirementDocInline]
Reference: https://stackoverflow.com/a/74233744/1388835

data of foreign keys are not saving in django admin nested inlines

I'm trying to build a list of replicable fields where the order can be interchanged.
To do so I've built three different models Multicap Multitext Multimg which are Inlines of the model Multis which is an Inline of the model Delta.
I'm using django-nested-admin and everything works fine on the admin page, I can add new objects and change their order.
The problem I have is that when I populate the fields, save the model and then check its content, all the data of the text fields are turned into zeros 0.
instead, when I try to save the image I get this error:
AttributeError: 'int' object has no attribute 'field'
models.py
class Multis(models.Model):
name = models.TextField(max_length=50, null=True, blank=True)
delta = models.ForeignKey('Delta', related_name="delta", null=True, on_delete=models.CASCADE)
class Meta:
ordering = ('name',)
def __str__(self):
return str(self.name)
class Multicap(models.Model):
caption = models.TextField(max_length=50, null=True, blank=True)
multic = models.ForeignKey('Multis', related_name="multicap", null=True, on_delete=models.CASCADE)
class Meta:
ordering = ('caption',)
def __str__(self):
return str(self.caption)
class Multimg(models.Model):
img = models.ImageField(upload_to="images", verbose_name='Image', null=True, blank=True,)
multim = models.ForeignKey('Multis', related_name="multimg", null=True, on_delete=models.CASCADE)
class Meta:
ordering = ('img',)
#property
def img_url(self):
if self.img and hasattr(self.img, 'url'):
return self.img.url
def get_image_filename(instance, filename):
title = instance.post.title
slug = slugify(title)
return "post_images/%s-%s" % (slug, filename)
def get_absolute_url(self):
return reverse('delta-detail', kwargs={'pk': self.pk})
class Multitext(models.Model):
text = tinymce_models.HTMLField(null=True, blank=True)
multit = models.ForeignKey('Multis', related_name="multitext", null=True, on_delete=models.CASCADE)
class Meta:
ordering = ('text',)
def __str__(self):
return str(self.text)
class Delta(models.Model):
heading = models.CharField(max_length=50, null="true")
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ('heading',)
def __str__(self):
return str(self.heading)
def get_absolute_url(self):
return reverse('delta-detail', kwargs={'pk': self.pk})
admin.py
from django.contrib import admin
import nested_admin
from nested_admin import SortableHiddenMixin, NestedTabularInline, NestedModelAdmin, NestedStackedInline
from .models import Delta, Multimg, Multitext, Multicap, Multis
class MimgAdmin(nested_admin.NestedStackedInline):
model = Multimg
sortable_field_name = "img"
extra = 0
class MtxtAdmin(nested_admin.NestedStackedInline):
model = Multitext
sortable_field_name = "text"
extra = 0
class McapAdmin(nested_admin.NestedStackedInline):
model = Multicap
sortable_field_name = "caption"
extra = 0
class MAdmin(nested_admin.SortableHiddenMixin, nested_admin.NestedStackedInline):
model = Multis
sortable_field_name = "name"
extra = 0
inlines = [ McapAdmin, MtxtAdmin, MimgAdmin ]
#admin.register(Delta)
class DeltaAdmin(nested_admin.NestedModelAdmin):
sortable_field_name = "delta"
inlines = [ MAdmin ]
Solved. It was a stupid error related to sortable_field_name
This field needs to be related to a field in the model which has to be formulated this way:
models.py
position = models.PositiveSmallIntegerField("Position", null=True)
admin.py
sortable_field_name = 'position'
This forms a position field that has a basic value of 0. Doing the way I was doing so this value was being substituted for the field I wanted to fill in.
Hope this can help someone occuring in the same error

Django - edit various number of formset and each form has own related values

I'm lost in django formsets. I tried many variations and none works as I need. Maybe it is a little bit confusing what my models are :)
What do I want to do? I need to create a view that displays all AssessParameters related to KapTSI and my problem is editing fields [assessment_requirements, value, finding]. Maximum what is was able to solve by using formset was editing those fields but how to display only the assessment_requirements those are related to edited parameter and to all parameters? And the bonus if there is a way with using CBV?
Models.py
class AssessParameter(models.Model):
application = models.ForeignKey(Application, on_delete=models.CASCADE, blank=True, null=True)
parameter = models.ForeignKey(Parameter, on_delete=models.DO_NOTHING)
requirement = models.TextField(blank=True)
assessment_requirements = models.ManyToManyField(Requirement, related_name="assessments", blank=True)
value = models.TextField(blank=True, null=True)
finding = models.ForeignKey(Finding, on_delete=models.DO_NOTHING)
note = models.TextField(blank=True)
documents = models.CharField(max_length=1, blank=True)
class KapTsi(models.Model):
title = models.CharField(max_length=150)
number = models.CharField(max_length=20)
tsi = models.ManyToManyField(Standard, related_name="tsis")
def __str__(self):
return f"{self.number} | {self.title}"
class ParameterGroup(models.Model):
title = models.CharField(max_length=150)
kap_tsi = models.ForeignKey(KapTsi, models.DO_NOTHING)
def __str__(self):
return f"{self.kap_tsi} {self.title}"
class Parameter(models.Model):
parameter_group = models.ForeignKey(ParameterGroup, on_delete=models.DO_NOTHING)
title = models.CharField(max_length=255)
standards = models.ManyToManyField(Standard, through="Specification", blank=True)
description = models.TextField(blank=True)
active = models.BooleanField(default=True)
def __str__(self):
return self.title
foms.py
class AssessParameterForm(forms.ModelForm):
class Meta:
model = AssessParameter
exclude = ['parameter', 'requirement', 'application']
AssessmentParameterFormSet = modelformset_factory(AssessParameter, form=AssessParameterForm, extra=0)
last try: views.py
def assessment_group(request, pk, slug, group):
application = Application.objects.get(id=pk)
group = ParameterGroup.objects.get(id=group)
assessments = AssessParameter.objects.filter(application=application).filter(parameter__parameter_group=group)
parameter = Requirement.objects.filter(parameter__parameter_group=group)
formset = AssessmentParameterFormSet(instance=assessments)
# for form in formset:
# form.fields['assessment_requirements'].queryset = parameter
context = {
'application': application,
'formset': formset,
}
return render(request, 'assessment/assessment-group.html', context)

how to add category to blog project django

i developed a blog project by watching many open-source courses and create my own django custom admin dashboard where i want to add a category option to my blog project, i have watched some tutorial on as well but couldn't find them helpful
models.py
from django.db import models
from django.forms import ModelForm
from farmingwave.models import BaseHeader,Submenu
class Category(models.Model):
mainmenu=models.ForeignKey(BaseHeader,null=True,on_delete=models.SET_NULL)
submenu=models.ForeignKey(Submenu,on_delete=models.CASCADE)
class AdSideMenu(models.Model):
title_id = models.AutoField(primary_key=True)
title_name = models.TextField()
url = models.TextField()
priority = models.IntegerField()
submenu_status = models.TextField()
class Meta:
db_table = 'admin_side'
class CreateBlog(models.Model):
id = models.AutoField(primary_key=True)
blog_Title = models.TextField(max_length=100)
content = models.TextField(max_length=5000)
category = models.ForeignKey(Category,null=True,on_delete=models.SET_NULL)
class Meta:
db_table = 'create_blog'
they are inhereting data from another app
models.py
`class BaseHeader(models.Model):
main_id = models.AutoField(primary_key=True)
title_name = models.TextField()
url = models.TextField()
priority = models.IntegerField()
submenu_status = models.TextField("false")
class Meta:
db_table = 'base_header'
class Submenu(models.Model):
sub_id = models.AutoField(primary_key=True)
main_id = models.IntegerField()
sub_name = models.TextField()
url = models.TextField()
priority = models.IntegerField()
mainmenu=models.ForeignKey(BaseHeader,on_delete=models.CASCADE)
class meta:
db_table = 'base_subheader'`
and the view function:
def create_blog(request):
if request.method =='POST':
form = CreateBlogForm(request.POST)
if form.is_valid():
form.save()
form = CreateBlogForm()
else:
form = CreateBlogForm()
base = BaseHeader.objects.all()
sub = Submenu.objects.all()
create = CreateBlog.objects.all()
category = Category.objects.all()
context = {
'form' : form,
'createblog' : create,
'category' : category,
'menu' : base,
'sub_menu' : sub,
Why not make the category a select item?
CATEGORY_CHOICES = (
('sports', 'sports'),
('tech', 'tech'),
('politics', 'politics')
)
category = models.CharField(max_length=100, choices=CATEGORY_CHOICES, blank=False)
You'd be able to access it like any other field now, so let's say the user clicked on "Politics articles" you can add a .filter(category="politics") and access it in the templates through {{ article.category }}
I don't know why there are all of these lines in your code, nor do I know the scale of your project, but that's how I would go about doing it.

save data to another table after creating django

i have two models ImageShoot and Image.
models.py:
class ImageShoot(models.Model):
name = models.CharField(max_length=100)
# image = models.URLField(name=None)
created_at = models.TimeField(auto_now_add=True)
def __str__(self):
return self.name
class Image(models.Model):
license_type = (
('Royalty-Free','Royalty-Free'),
('Rights-Managed','Rights-Managed')
)
image_number = models.CharField(default=random_image_number,max_length=12)
title = models.CharField(max_length = 100)
image = models.ImageField(upload_to = 'home/tboss/Desktop/image' , default = 'home/tboss/Desktop/image/logo.png')
category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE)
shoot = models.ForeignKey(ImageShoot, on_delete=models.CASCADE)
image_keyword = models.TextField(max_length=1000)
credit = models.CharField(max_length=150, null=True)
location = models.CharField(max_length=100, null=True)
license_type = models.CharField(max_length=20,choices=license_type, default='')
uploaded_at = models.TimeField(auto_now_add=True)
def __str__(self):
return self.title
admin.py:
class Imageset(admin.ModelAdmin):
associated_images = ImageShoot.image_set.all()
return associated_images
admin.site.register(Image)
admin.site.register(ImageShoot,Imageset)
what i am trying to achieve that when i create a image it should show on imageshoot also like when i create image in shoot 1. this image should show on shoot 1.
i am not sure which field should i add on imageshoot.
Use Reverse lookup
In Your views you can get all the images associated with the ImageShoot Obj using set.Try this in your shell after briefly going through the docs
associated_images = ImageShoot.image_set.all()
You can also use django orm methods for querysets like filter, count, etc.
Edit:
To display related images you can use this in admin:
#admin.register(ImageShoot)
class Imageset(admin.ModelAdmin):
list_display = ('name', 'created_at', 'associated_images')
def associated_images(self, obj):
return obj.image_set.all() #<----edit
associated_images.admin_order_field = 'imageshoot_image'