custom ordering to django model - python

class MemberAdmin(CustomUserAdmin, admin.ModelAdmin):
redirect_model_name = 'memberaccountproxy'
change_form_template = 'loginas/change_form.html'
list_display = ('username', 'email', 'first_name', 'last_name','country', 'gender',
'created_at', 'profile_pic')
search_fields = ('username', 'first_name', 'last_name', 'email',)
add_form = AccountProfileForm
list_filter = (
'gender', 'incomplete', 'email_verified', 'suspended',
'deleted',
)
# profile1 = None
def get_queryset(self, objects):
return Account.objects.filter(usertype=1)
def country(self, obj):
profile1 = Profile.objects.get(account=obj)
if profile1.country:
return profile1.country
return ''
country.admin_order_field = 'country'
What I am trying to achieve is to make my country column on Member list page sortable.(currently its not)
Problem is that I get the 'obj' from method country as an Account object(as defined in the get_queryset()), & later I use that obj to get another object of type Profile (which has a member variable country). But when I try to register the country method to 'admin_order_field', it can only take member variables of obj (of type Account, which doesn't have country variable in it).
Is there a way to sort the country column based on the field from Profile class instead of Account.
class Profile(models.Model):
account = models.OneToOneField(Account)
country = models.ForeignKey('Country', null=True, blank=True, verbose_name='Country Living In', related_name='+')
# name = models.CharField(max_length=40, blank=True)
status = models.ForeignKey('Status', blank=True, null=True, verbose_name='Marital Status', related_name='+')
btype = models.ForeignKey('Btype', blank=True, null=True, verbose_name='Body type', related_name='+')
bheight = models.IntegerField(choices=HEIGHT, blank=True, null=True, verbose_name='Height')
phystatus = models.ForeignKey('EthnicOrigin', blank=True, null=True, verbose_name='Ethnic Origin', related_name='+')
createdby = models.ForeignKey('CreatedBy', blank=True, null=True, verbose_name='Profile Created By',
related_name='+')
...........................
class Account(AbstractBaseUser):
email = models.EmailField(unique=True)
usertype = models.IntegerField(default=1, choices=USER)
username = models.CharField(max_length=40, unique=True)
gender = models.CharField(choices=(('Male', 'Male'), ('Female', 'Female')), max_length=10, blank=True)
phone = models.CharField(max_length=16, blank=True, verbose_name="Mobile No", null=True)
temple = models.ManyToManyField('Account', blank=True, null=True, verbose_name="MatchMaker")
first_name = models.CharField(max_length=40, blank=True, null=True)
last_name = models.CharField(max_length=40, blank=True, null=True)
acc_for = models.ForeignKey('CreatedBy', blank=True, null=True, verbose_name="Profile Created For")
country_code = models.ForeignKey('CountryCode', max_length=40, blank=True, null=True)
............................................

The list_display and admin_order_field option supports double underscore notation to access related models.
Your question isn't clear because you haven't shown your models, but it looks like you can do:
country.admin_order_field = 'profile__country'
However, you can probably replace country with profile__country in your list_display method, and remove your country method entirely.

Related

Initial data not working if I hide some one-to-many fields in django

I want to prefill some one to many fields and also hide these field because I want to avoid a scenario where a user can see all the records related to the fields. The problem I'm facing is when I use 'all' on the form fields I the initial data dictionary is working well, but if I try to use a list of the fields I want displayed, the initial data is not getting passed into the form.
Here is my models.py:
class Agent(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL)
first_name = models.CharField(max_length=15, null=True, blank=True,)
surname = models.CharField(max_length=15, null=True, blank=True,)
provcoord = models.ForeignKey(Provcoord, null=True, blank=True, on_delete=SET_NULL)
regcoord = models.ForeignKey(Regcoord, null=True, blank=False, on_delete=SET_NULL)
region = models.CharField(max_length=15, null=False, blank=True, choices=REGION)
province = models.CharField(max_length=15, null=False, blank=False, choices=PROVINCE)
id_no = id_no = models.CharField(max_length=10, null=False, blank=False, unique=True,)
agent_no = models.CharField(default="Not Assigned", max_length=20, null=False, blank=False)
address = models.TextField(null=False, blank=False)
gender = models.CharField(max_length=20, null=False, blank=False, choices=GENDER)
profile_pic = models.ImageField(upload_to="assets", default="default.png")
is_blacklisted = models.BooleanField(default=False)
reason_for_blacklist = models.TextField(max_length=500, null=True, blank=True)
registered_at = models.DateTimeField(auto_now_add=True)
def get_absolute_url(self):
return reverse("agent", kwargs={'str' :str.id})
def __str__(self):
return self.user.username
class Adult(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
agent = models.ForeignKey(Agent, null=True, blank=True, on_delete=SET_NULL)
regcoord = models.ForeignKey(Regcoord, null=True, blank=True, on_delete=SET_NULL)
provcoord = models.ForeignKey(Provcoord, null=True, blank=True, on_delete=SET_NULL)
surname = models.CharField(max_length=150, null=False, blank=False)
first_name = models.CharField(max_length=150, null=False, blank=False)
other_name = models.CharField(max_length=150, null=True, blank=True)
address = models.CharField(max_length=200, null=True, blank=True)
region = models.CharField(max_length=15, null=True, blank=True,choices=PROVINCE)
dob = models.CharField(max_length=10, null=False, blank=False)
gender = models.CharField(max_length=20, null=False, blank=False, choices=GENDER)
id_no = models.CharField(max_length=12, null=False, blank=False, unique=True)
receipt_no = models.CharField(max_length=10, default="Not Receipted", null=True,
blank=True)
phone_no = models.CharField(max_length=20, null=False, blank=False,)
marital_status = models.CharField(max_length=20, null=False, blank=False, choices=MARITAL_STATUS)
views.py:
def add_parent(request,):
agent = request.user.agent
regcoord = request.user.agent.regcoord
provcoord = request.user.agent.provcoord
region = request.user.agent.region
province = request.user.agent.province
form = ParentForm(initial={
'agent' :agent,
'regcoord' :regcoord,
'provcoord' :provcoord,
'region' :region,
'province' :province
})
if request.method == 'POST':
form = ParentForm(request.POST, request.FILES,)
if form.is_valid():
form.save()
return redirect('/')
context = {'form' :form}
return render(request, 'kyc/add_adult.html', context)
forms.py:
class ParentForm(ModelForm):
class Meta:
model = Adult
fields = ['surname',
'first_name',
'other_name',
'address',
'dob',
'gender',
'id_no',
'receipt_no',
'phone_no',
'image'
]
Please Help on how I can get around this issue.
Here is an approach I suggest (not tested though):
from django import forms
class ParentForm(ModelForm):
agent = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))
regcoord = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))
provcoord = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))
region = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))
province = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(ParentForm, self).__init__(*args, **kwargs)
self.fields['agent'].initial = self.user.agent
self.fields['regcoord'].initial = self.user.regcoord
self.fields['provcoord'].initial = self.user.provcoord
self.fields['region'].initial = self.user.region
self.fields['province'].initial = self.user.province
class Meta:
model = Adult
fields = ['surname',
'first_name',
'other_name',
'address',
'dob',
'gender',
'id_no',
'receipt_no',
'phone_no',
'image'
]
Notes how I referenced the 5 fields (agent, regcoord, provcoord, region, province) as extra fields by declaring them as simple CharFields. So they are no longer rendered from the model as dropdown lists. Then in the method __init__ I define the initial values ​​for each of the fields.
Your function add_parent should become:
def add_parent(request,):
form = ParentForm(user=request.user)
if request.method == 'POST':
form = ParentForm(request.POST, request.FILES,)
if form.is_valid():
form.save()
return redirect('/')
context = {'form' :form}
return render(request, 'kyc/add_adult.html', context)
Edit
Here is another alternative:
def add_parent(request,):
data = {'agent': request.user.agent, 'regcoord': request.user.regcoord, 'provcoord': request.user.provcoord, 'region': request.user.region, 'province': request.user.province}
form = ParentForm(initial=data)
if request.method == 'POST':
form = ParentForm(request.POST, request.FILES,)
if form.is_valid():
form.save()
return redirect('/')
context = {'form' :form}
return render(request, 'kyc/add_adult.html', context)
In the function add_parent, I pass the initial values ​​in the form of a dictionary (data), to the variable initial.
Then you need to remove the __init__ method from your form. Django will take care of rendering the form with the initial values ​​in the corresponding fields.

tabular inline admin where table are referenced in multiple tables

I was looking on customizing admin where i found tabularinline model which allow us to edit on the same page. But i got confused as my tables are reference in multiple places. I could not understand which model should i make tabular inline.
for example here is my model
class ProductType(ModelWithMetadata):
name = models.CharField(max_length=150, help_text="type of product. ex - accessories, apparel")
slug = models.SlugField(max_length=150, unique=True)
is_shipping_required = models.BooleanField(default=True)
class Meta:
ordering = ("slug",)
app_label="products"
class Category(MPTTModel, ModelWithMetadata):
name = models.CharField(max_length=128)
slug = models.SlugField(max_length=128)
description = models.TextField(blank=True)
parent = models.ForeignKey(
"self", null=True, blank=True, related_name="children", on_delete=models.CASCADE
)
objects = models.Manager()
tree = TreeManager()
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
def __str__(self):
return self.name
class Product(ModelWithMetadata, PublishableModel):
product_type = models.ForeignKey(
ProductType, related_name="products", on_delete=models.CASCADE
)
name = models.CharField(max_length=128)
slug = models.SlugField()
category = models.ForeignKey(
Category,
related_name="products",
on_delete=models.SET_NULL,
null=True,
blank=True,
)
isAvailable = models.BooleanField(default=True)
isDiscount = models.BooleanField(default=False)
charge_taxes = models.BooleanField(default=False)
updated_at = models.DateTimeField(auto_now=True, null=True)
class Meta:
verbose_name = "product"
verbose_name_plural = "products"
ordering = ("name",)
constraints = [
models.UniqueConstraint(
fields=["article_number", "slug"], name="unique article number and slug")
]
class ProductVariant(ModelWithMetadata):
sku = models.CharField(max_length=255, unique=True)
name = models.CharField(max_length=255, blank=True)
currency = models.CharField(
max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
default=settings.DEFAULT_CURRENCY,
blank=True,
null=True,
)
price_override_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
blank=True,
null=True,
)
product = models.ForeignKey(
Product, related_name="variants", on_delete=models.CASCADE
)
images = models.ManyToManyField("ProductImage", through="VariantImage")
track_inventory = models.BooleanField(default=True)
class BaseAssignedAttribute(models.Model):
assignment = None
values = models.ManyToManyField("AttributeValue")
class AttributeValue(models.Model):
name = models.CharField(max_length=250)
value = models.CharField(max_length=100, blank=True, default="")
slug = models.SlugField(max_length=255)
attribute = models.ForeignKey(
"Attribute", related_name="values", on_delete=models.CASCADE
)
class AssignedProductAttribute(BaseAssignedAttribute):
"""Associate a product type attribute and selected values to a given product."""
product = models.ForeignKey(
Product, related_name="attributes", on_delete=models.CASCADE
)
assignment = models.ForeignKey(
"ProductAttribute", on_delete=models.CASCADE, related_name="productassignments"
)
class Meta:
unique_together = (("product", "assignment"),)
class AssignedVariantAttribute(BaseAssignedAttribute):
"""Associate a product type attribute and selected values to a given variant."""
variant = models.ForeignKey(
ProductVariant, related_name="attributes", on_delete=models.CASCADE
)
assignment = models.ForeignKey(
"AttributeVariant", on_delete=models.CASCADE, related_name="variantassignments"
)
class Meta:
unique_together = (("variant", "assignment"),)
class AttributeVariant(models.Model):
attribute = models.ForeignKey(
"Attribute", related_name="attributevariant", on_delete=models.CASCADE
)
product_type = models.ForeignKey(
ProductType, related_name="attributevariant", on_delete=models.CASCADE
)
assigned_variants = models.ManyToManyField(
ProductVariant,
blank=True,
through=AssignedVariantAttribute,
through_fields=("assignment", "variant"),
related_name="attributesrelated",
)
class Attribute(models.Model):
name = models.CharField(max_length=30, unique=True)
slug = models.SlugField(max_length=250, unique=True)
product_types = models.ManyToManyField(
ProductType,
blank=True,
related_name="product_attributes",
through="ProductAttribute",
through_fields=("attribute", "product_type"),
)
product_variant_types = models.ManyToManyField(
ProductType,
blank=True,
related_name="variant_attributes",
through=AttributeVariant,
through_fields=("attribute", "product_type"),
)
class ProductAttribute(models.Model):
attribute = models.ForeignKey(
"Attribute", related_name="attributeproduct", on_delete=models.CASCADE
)
product_type = models.ForeignKey(
ProductType, related_name="attributeproduct", on_delete=models.CASCADE
)
assigned_products = models.ManyToManyField(
Product,
blank=True,
through=AssignedProductAttribute,
through_fields=("assignment", "product"),
related_name="attributesrelated",
)
I am confused on the tables AttributeValue, AssignedProductAttribute, AssignedVariantAttribute, AttributeVariant, Attribute and ProductAttribute. Attribute is related to ProductAttribute and is also related to AttributeVariant and AttributeValue. Similarly, in the case of variant.
I could not figure out which table should be inline and where should i reference that inlined table. Because of various relationship, i am not sure of those things.

Django Admin error using inline, please correct the errors below

I'm relatively new to Django and I'm currently leveraging the built in admin app. I am receiving the following error whenever I try to add/save an inline child group and whenever I do a simple edit to the parent:
please correct the errors below
If I don't include the inline...adds, edits and deletes work fine. I'm not too sure how to resolve this. I've tried a few things based on what is available via google search, but still have not come to a resolution.
Here is a snippet of my model:
class Group(models.Model): # Parent
groupid = models.CharField('Group ID',db_column='groupId', primary_key=True, auto_created=True, default=uuid.uuid4, max_length=36) # Field name made lowercase.
groupabbr = models.CharField('Group Abbr',db_column='groupAbbr', max_length=30) # Field name made lowercase.
groupname = models.CharField('Group Name',db_column='groupName', max_length=100) # Field name made lowercase.
groupemail = models.EmailField('Group Email',db_column='groupEmail', max_length=200, blank=True, null=True) # Field name made lowercase.
# description = models.TextField(db_column='description', max_length=255, blank=True, null=True)
description = models.CharField(db_column='description', max_length=255, blank=True, null=True)
fkpripocpersonid = models.ForeignKey(Person,db_column='fkPriPocPersonId', related_name='priPocForGroups', on_delete=models.SET_NULL, max_length=36, blank=True, null=True, verbose_name='Primary POC') # Field name made lowercase.
fksecpocpersonid = models.ForeignKey(Person,db_column='fkSecPocPersonId', related_name='secPocForGroups', on_delete=models.SET_NULL, max_length=36, blank=True, null=True, verbose_name='Secondary POC') # Field name made lowercase.
primaryfieldtitle = models.CharField('Primary Field Title',db_column='primaryFieldTitle', max_length=100, blank=True, null=True) # Field name made lowercase.
primaryfieldcontent = models.TextField('Primary Field Content',db_column='primaryFieldContent', blank=True, null=True) # Field name made lowercase.
secondaryfieldtitle = models.CharField('Secondary Field Title',db_column='secondaryFieldTitle', max_length=100, blank=True, null=True) # Field name made lowercase.
secondaryfieldcontent = models.TextField('Secondary Field Content',db_column='secondaryFieldContent', blank=True, null=True) # Field name made lowercase.
createddate = models.DateTimeField('Date Created',db_column='createdDate', default=datetime.now()) # Field name made lowercase.
createdby = models.ForeignKey(Person, db_column='createdBy', related_name='createdGroups', on_delete=models.SET_NULL, max_length=36, null=True, verbose_name='Created By') # Field name made lowercase.
archiveddate = models.DateTimeField('Date Archived',db_column='archivedDate',
default=datetime.now(), blank=True, null=True) # Field name made lowercase.
archivedby = models.ForeignKey(Person, db_column='archivedBy', related_name='archivedGroups', on_delete=models.SET_NULL, max_length=36, blank=True, null=True, verbose_name='Archived By') # Field name made lowercase.
fkparentgroupid = models.ForeignKey('self', db_column='fkParentGroupId', related_name='Parents',
on_delete=models.CASCADE, null=True, verbose_name='Parent Group',
max_length=36, blank=True)
def __str__(self): # this object's representation used throughout Django
return self.groupabbr + ' - ' + self.groupname
class Meta:
managed = False
db_table = 'tbl_group'
ordering = ('groupname',)
Here is a snippet of my Admin.py:
class GroupInline(admin.TabularInline):
model = Group
classes = ['collapse']
exclude = ['groupemail','primaryfieldtitle', 'primaryfieldcontent',
'archiveddate', 'archivedby', 'createddate', 'createdby', 'secondaryfieldtitle',
'secondaryfieldcontent',]
"""list_display = ('groupid', 'groupabbr','groupname', 'description', 'fkpripocpersonid', 'fksecpocpersonid',
'createddate', 'createdby') """
list_editable = ('groupid', 'groupabbr','groupname', 'description', 'fkpripocpersonid', 'fksecpocpersonid',
'createddate', 'createdby')
extra = 0
class GroupExistingInline(admin.TabularInline):
model = Group
classes = ['collapse']
exclude = ['groupemail','primaryfieldtitle', 'primaryfieldcontent',
'archiveddate', 'archivedby', 'createddate', 'createdby', 'secondaryfieldtitle',
'secondaryfieldcontent', 'groupid',]
readonly_fields = ('groupabbr','groupname', 'description', 'fkpripocpersonid', 'fksecpocpersonid',
'createddate', 'createdby')
extra = 0
def has_add_permission(self, request):
return False
class GroupAdmin(admin.ModelAdmin, ExportCsvMixin):
list_display = ('groupabbr','groupname', 'fkparentgroupid', 'fkpripocpersonid', 'fksecpocpersonid')
list_filter = ('groupname',)
actions = ["export_as_csv"]
inlines = [GroupExistingInline, GroupInline, ]
fieldsets = [
(None, {'fields': ('fkparentgroupid', ('groupname', 'groupabbr'),
'description', 'groupemail', ('fkpripocpersonid', 'fksecpocpersonid',), ('createddate',
'createdby'),)}),
('Primary Content', {
'classes': ('collapse',), # collapse, wide, extrapretty
'fields': ['primaryfieldtitle', 'primaryfieldcontent', ],
}),
('Secondary Content', {
'classes': ('collapse',), # collapse, wide, extrapretty
'fields': ['secondaryfieldtitle', 'secondaryfieldcontent', ],
}),
]
def __init__(self, model, admin_site):
self.form.admin_site = admin_site
super(GroupAdmin, self).__init__(model, admin_site)
def get_actions(self, request):
actions = super().get_actions(request)
if 'delete_selected' in actions:
del actions['delete_selected']
return actions
admin.site.register(Group, GroupAdmin)

Django Admin, All the contents of my table are not being displayed & Inline Issue

Attached below is the models.py I used for my project,
I've attached the photos of the issue as well.
Issue 1
For some reason, all the contents of the tables are not being displayed.
In the first table, first content goes missing.
In the Second table, First and the second contents go missing
Issue 2
The Inline function doesn't work. I tried going through the documentation and several youtube videos to find out how to handle the situation but it didn't help much.
Issue 3
For the bug table, When I select the project name, How do I ensure that only the people I added to that project table are allowed to be selected?
Issue 4
Is there a way to extract the email ID from the Users page and and when I choose the name of the user in the Project page, the email Id will be automatically filled it?
Same way, In the issues page, when I choose the user, the email Id will be auto entered.
MODELS.py
from django.db import models
# Create your models here.
from django.contrib.auth.models import User
from django.db import models
from django.core.mail import EmailMessage
from django.contrib import admin
# Create your models here.
class Project(models.Model):
STATUS_CHOICE = (
('Project Manager', 'Project Manager'),
('Technician', 'Technician'),
('Tester', 'Tester')
)
STATUS_CHOICE_1 = (
('Work Assigned', 'Work Assigned'),
('Work in Progress', 'Work in Progress'),
('Testing', 'Testing'),
('Completed', 'Completed')
)
Project_Name = models.CharField(max_length=100)
Project_Description = models.CharField(max_length=100)
Admin_Name = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Admin_Name_users+')
Admin_Mail_ID = models.EmailField(max_length=50)
Project_Manager_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Project_Manager_1_users+')
Project_Manager_1_Mail_ID = models.EmailField(max_length=50)
Project_Manager_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Project_Manager_2_users+', blank=True, null=True)
Project_Manager_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Technician_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Technician_1_users+')
Technician_1_Mail_ID = models.EmailField(max_length=50)
Technician_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Technician_2_users+', blank=True, null=True)
Technician_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Technician_3 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Technician_3_users+', blank=True, null=True)
Technician_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Tester_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Tester_1_users+')
Tester_1_Mail_ID = models.EmailField(max_length=50, default='Example#gmail.com')
Additional_User_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Ad_1_users+', blank=True, null=True)
Additional_User_1_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
Additional_User_1_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Additional_User_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Ad_1_users+', blank=True, null=True)
Additional_User_2_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
Additional_User_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Additional_User_3 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Ad_1_users+', blank=True, null=True)
Additional_User_3_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
Additional_User_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Status_of_the_project = models.CharField(max_length=18, choices=STATUS_CHOICE_1)
Created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
Finish_Date = models.DateTimeField(null=True, blank=True)
Supporting_Documents = models.FileField(null=True, blank=True)
class FlatPageAdmin(admin.ModelAdmin):
fieldsets = (
(None, {
'fields': ('Project_Name','Project_Description','Admin_Name','Admin_Mail_ID','Project_Manager_1','Project_Manager_1_Mail_ID',
'Technician_1','Technician_1_Mail_ID','Tester_1','Tester_1_Mail_ID','Status_of_the_project','Created','Finish_Date','Supporting_Documents',
)
}),
('Add More Users', {
'classes': ('collapse',),
'fields': ('Project_Manager_2','Project_Manager_2_Mail_ID','Technician_2','Technician_2_Mail_ID',
'Technician_3','Technician_3_Mail_ID','Additional_User_1','Additional_User_1_Type',
'Additional_User_1_Mail_ID','Additional_User_2','Additional_User_2_Type','Additional_User_2_Mail_ID',
'Additional_User_3','Additional_User_3_Type','Additional_User_3_Mail_ID'),
}),
)
def __str__(self):
return self.Project_Name
class Meta:
verbose_name_plural = "List Of Projects"
class Bug(models.Model):
STATUS_CHOICE = (
('Unassigned', 'Unassigned'),
('Assigned', 'Assigned'),
('Testing', 'Testing'),
('Tested', 'tested'),
('Fixed', 'Fixed')
)
STATUS_CHOICE_1 = (
('Bug', 'Bug'),
('Issue', 'Issue'),
('Enhancement', 'Enhancement'),
('Not an issue or bug', 'Not an issue or bug'),
('Fixed', 'Fixed')
)
Project = models.ForeignKey(Project, on_delete=models.CASCADE)
Issue_Title = models.CharField(max_length=50, blank=True, null=True)
Situation_Type = models.CharField(max_length=25, choices=STATUS_CHOICE_1)
Basic_Description = models.CharField(max_length=100)
Detailed_Description = models.TextField(default='The Description, here.')
Status = models.CharField(max_length=18, choices=STATUS_CHOICE)
Assigned_to = models.ForeignKey(User, on_delete=models.CASCADE)
Assigned_to_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Admin_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Reported_by = models.CharField(max_length=50, blank=True, null=True)
Reporters_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Reported_Date = models.DateTimeField(null=True, blank=True)
Created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
Updated = models.DateTimeField(auto_now=True, null=True, blank=True)
Deadline_Date = models.DateTimeField(null=True, blank=True)
Supporting_Documents_By_Reporter = models.FileField(null=True, blank=True)
Project_Managers_Comment = models.TextField(default='The Description, here.')
Supporting_Documents_by_Project_Manager = models.FileField(null=True, blank=True)
Technicians_Comment = models.TextField(default='The Description, here.')
Supporting_Documents_by_Technician = models.FileField(null=True, blank=True)
Testers_Comment = models.TextField(default='The Description, here.')
Supporting_Documents_by_Tester = models.FileField(null=True, blank=True)
def __str__(self):
return '{} ({}) [{}]'.format(self.Project, self.Situation_Type, self.Status, self.Issue_Title)
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
if self.id:
user=self.Assigned_to
self.Assigned_to_Mail_ID=user.email
send_mail(self.Admin_Mail_ID, ass=self.Assigned_to_Mail_ID)
super(Bug, self).save()
class Meta:
verbose_name_plural = "Projects Tasks/Issues"
def send_mail(admin,ass):
email=EmailMessage('Changes made to Task','Changes have been made to one of your Task reports and we hereby request you to have a look at it at the earliest.', to=[admin,ass])
email.send()
I've also attached the admin.py file as well.
Admin.py
from django.contrib import admin
from .models import Bug, Project
from django.contrib.admin.models import LogEntry
admin.site.register(LogEntry)
# Register your models here.
class BugDisplay(admin.ModelAdmin):
list_display = ('Project', 'Status', 'Basic_Description', 'Assigned_to', 'Created', 'Updated', 'Issue_Title')
list_filter = ('Status', 'Assigned_to', 'Project')
search_fields = ('Reporters_Mail_ID', 'Reported_by', 'Basic_Description',)
admin.site.register(Bug, BugDisplay)
# Register your models here.
#admin.register(Project)
class ProjectDisplay(admin.ModelAdmin):
list_display = ('Project_Name','Admin_Name', 'Project_Manager_1', 'Status_of_the_project')
list_filter = ('Admin_Name', 'Status_of_the_project')
search_fields = ('Project_Name', 'Project_Description', 'Admin_Name', 'Admin_Mail_ID', 'Project_Manager_1 '
'Project_Manager_1_Mail_ID', 'Project_Manager_2 ', 'Project_Manager_2_Mail_ID',
'Technician_1',
'Technician_1_Mail_ID', 'Technician_2', 'Technician_2_Mail_ID', 'Technician_3',
'Technician_3_Mail_ID', 'Tester_1', 'Tester_1_Mail_ID', 'Additional_User_1', 'Additional_User_1_Type',
'Additional_User_1_Mail_ID', 'Additional_User_2', 'Additional_User_2_Type', 'Additional_User_2_Mail_ID',
'Additional_User_3', 'Additional_User_3_Type', 'Additional_User_3_Mail_ID', 'Status_of_the_project', 'Created',
'Finish_Date', 'Supporting_Documents')
As per your question please provide your admin inline class (referring to issue 2) and please elaborate for issue 1 and provide more details.
Regarding issue 2 you can override appropriate field using this. You can provide your custom queryset(by applying your filter conditions) to the foreign key field.
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == 'your_field_name':
kwargs["queryset"] = your_custom_queryset_based_on_conditions
return super().formfield_for_foreignkey(db_field, request, **kwargs)
For issue 4, you want email Id to be auto filled based on user selection. This can be achieved using custom javascript.
Another way could be that, you do not show email field and while saving the record from project/issue admin you automatically fetch email id from users table and assign it to the object and save it.
You may have a look at this, to customize while saving the object from admin panel.
def save_model(self, request, obj, form, change):
email = your_method_to_find_email_for_user(obj.user_field)
obj.email_field = email
super().save_model(request,obj,form,change)

Customizing inline foreign key with no repetition

i have these models:
models.py
class Offer(BaseModel):
code = models.CharField(_("Codice Offerta"), max_length=16, blank=False, null=False, default=0, editable=False)
company = models.ForeignKey(Company, verbose_name=_('Azienda'), related_name='company')
outcome = models.CharField(_('Esito Offerta'), choices=OUTCOME, max_length=64, blank=True, null=True)
user = models.CharField(_("Inserita da"), max_length=64, blank=False, null=True)
class Product(BaseModel):
name = models.CharField(_("Nome Prodotto"),max_length=1024, blank = False, null=True)
category = models.CharField(_("Categoria"),max_length=1024, blank = False, null=True, choices=CATEGORY)
class ProductOfferDoc(BaseModel):
product = models.CharField(max_length=1024, blank=False,null=False, choices=DOC)
number = models.IntegerField(_('Num.'), default=0, blank=True, null=True)
price = models.DecimalField(_('Prezzo'),max_digits=10, decimal_places=2,default=0.00,blank=True, null=True )
offer = models.ForeignKey(Offer, related_name='related_doc')
admin.py
class DocAdmin(admin.StackedInline):
extra = 1
model = ProductOfferDoc
class OfferAdmin(admin.ModelAdmin):
model = Offer
list_display = ['code','company']
inlines = [
DocAdmin,
CourseAdmin,
RiskAdmin,
ServiceAdmin,
SanitaryAdmin,
]
When I create an offer, I can add as many ProductOfferDoc as I want because this is a foreign key, but I don't want to allow to insert the same ProductOfferDoc multiple times. Where can I make these controls over the form?
You can use models.OneToOneField:
class ProductOfferDoc(BaseModel):
# ...
offer = models.OneToOneField(Offer, related_name='related_doc')

Categories