I have a Course model with Option as ClusterableModel and Staff. Staff is related to Course model and Staf can choose the Option. I've done it similar things before with normal django, but I can't seems to figure out how to do it with Wagtail. The Option is showing normally on Course's Page but its empty on Staff's Tab. Here is my model :
class Option(models.Model):
name = models.CharField(max_length=255)
desc = models.CharField(max_length=255, blank=True, null=True)
class Meta:
abstract = True
def __str__(self):
return self.name
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
self.tajuk = self.name.title()
content_panels = [
FieldPanel('name'),
FieldPanel('desc')
]
class OptionPage(Orderable, Option):
page = ParentalKey("Course", related_name='course_option')
class Staf(Orderable):
page = ParentalKey('course.Course', related_name='pcourse')
jxr = models.ForeignKey('jxr.Staf',
null=True,
blank=True,
on_delete=models.PROTECT,
related_name='+'
)
vegetarian = models.BooleanField(default=False)
attend = models.BooleanField(default=False)
reason = models.CharField(max_length=255, blank=True, null=True)
replacement = models.ForeignKey('jxr.Staf',
null=True,
blank=True,
on_delete=models.PROTECT,
related_name='+'
)
option = models.ForeignKey(OptionPage,blank=True, null=True)
class Meta:
verbose_name_plural = 'Staf'
panels = [
FieldPanel('jxr'),
FieldPanel('vegetarian'),
FieldPanel('option'),
FieldPanel('attend'),
FieldPanel('reason'),
FieldPanel('replacement'),
]
class Course(Page):
tags = ClusterTaggableManager(through=CourseTag, blank=True)
picture = models.ForeignKey(
'wagtailimages.Image',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
State = models.ForeignKey(State, default=1,
related_name='+',
on_delete=models.PROTECT,
)
location = RichTextField()
start = models.DateTimeField("Start",default=timezone.now)
end = models.DateTimeField("End", default=timezone.now)
max_staf = models.PositiveIntegerField(default=1)
intro = StreamField(CourseBlock())
status = models.CharField(max_length=30, choices=STATUS_KURSUS)
search_fields = Page.search_fields + [
index.SearchField('title'),
index.SearchField('intro')]
parent_page_types =['course.CourseIndex']
subpage_types=[]
content_panels = [
FieldPanel('title', classname="full title"),
MultiFieldPanel([
InlinePanel('kat_kursus', label='Category'),
FieldPanel('tags'),
InlinePanel('course_option', label='Options')
]),
ImageChooserPanel('picture'),
FieldPanel('state'),
FieldPanel('location'),
FieldPanel('start'),
FieldPanel('end'),
FieldPanel('max_staf'),
StreamFieldPanel('intro'),
FieldPanel('status'),
]
staf_panel = [
InlinePanel('pkursus', label='Staf')
]
edit_handler = TabbedInterface([
ObjectList(content_panels, heading='Content'),
ObjectList(staf_panel, heading='Staf'),
ObjectList(Page.promote_panels, heading='Promote'),
ObjectList(Page.settings_panels, heading='Settings', classname="settings"),
])
Related
I've already done this method in django. But I wanna convert this in django-rest-framework. I'm not how to do this can any one help me regarding this . I want to know how to build the serializers and views for this.
At the same time how to send additional data in this itself
sorry the code being dirty
thank you in advance...
models.py
class User(AbstractUser):
ADDCHKS_ID=models.CharField(max_length=16, blank=True, null=True)
is_active=models.BooleanField(default=False,blank=True, null=True)
is_excutive=models.BooleanField(default=False,blank=True, null=True)
class ExcutiveRegistration(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,null=True)
'''Personal Details'''
First_name = models.CharField(max_length=100,null=True ,blank=True)
Last_name = models.CharField(max_length=100,null=True ,blank=True)
DOB = models.DateField(max_length=100,null=True ,blank=True)
Fathers_name = models.CharField(max_length=100,null=True ,blank=True)
Contact_number = models.IntegerField(max_length=10,null=True ,blank=True)
Alt_Contact_number = models.IntegerField(max_length=10,null=True ,blank=True)
# Profile_picture=models.ImageField(upload_to='images/', null=True, verbose_name="")
'''Current Addresss'''
Pin_code_c = models.IntegerField(max_length=6,null=True ,blank=True)
State_c = models.CharField(max_length=50,null=True ,blank=True)
District_c = models.CharField(max_length=50,null=True ,blank=True)
Taluk_c = models.CharField(max_length=50,null=True ,blank=True)
Location_c = models.CharField(max_length=100,null=True ,blank=True)
House_no_c = models.IntegerField(max_length=4,null=True ,blank=True)
Street_c = models.CharField(max_length=100,null=True ,blank=True)
'''Permanent Address'''
Pin_code_p = models.IntegerField(max_length=6, null=True,blank=True)
State_p = models.CharField(max_length=50, null=True,blank=True)
District_p = models.CharField(max_length=50, null=True,blank=True)
Taluk_p = models.CharField(max_length=50, null=True,blank=True)
Location_p = models.CharField(max_length=100, null=True,blank=True)
House_no_p = models.IntegerField(max_length=4, null=True,blank=True)
Street_p = models.CharField(max_length=100, null=True,blank=True)
'''Reference'''
Family_reference_name = models.CharField(max_length=100, null=True,blank=True)
Family_reference_conatact_number = models.IntegerField(max_length=10, null=True,blank=True)
Neighbour_reference_name = models.CharField(max_length=100, null=True,blank=True)
Neighbour_reference_contact = models.IntegerField(max_length=10, null=True,blank=True)
'''Document Proof'''
ID_Proof_Document_Type=models.CharField(max_length=50,
choices=ID_CHOICES,
default="Voter",
null=True,
blank=True)
# ID_Proof_Document= models.ImageField(upload_to='images/', null=True, verbose_name="")
'''Bank Details'''
# Account_Name=models.CharField(max_length=50, null=True)
# Bank_name=models.CharField(max_length=50, null=True)
# Account_Number=models.CharField(max_length=50, null=True)
# IFSC_Code=models.IntegerField(max_length=15, null=True)
'''Area Covered'''
Work_State=models.CharField(max_length=50,null=True ,blank=True)
Work_covering_district=models.CharField(max_length=50,null=True ,blank=True)
Working_location=models.CharField(max_length=50,null=True ,blank=True)
Status=models.CharField(max_length=50,
choices=Status_,
default='No Action',
null=True
,blank=True)
def __str__(self):
return str(self.First_name)
class ExcutiveRegistrationPincode(models.Model):
ExcutiveRegistration=models.ForeignKey(ExcutiveRegistration, on_delete=models.CASCADE)
Covering_Pincode=models.IntegerField(max_length=6)
views.py
class ExcutiveHomeView(LoginRequiredMixin, ListView):
context_object_name = 'customers'
template_name = 'accounts/excutive/excutive_home_page.html'
def get_queryset(self, *args, **kwargs):
pincodes = [
e.Covering_Pincode
for e in ExcutiveRegistrationPincode.objects.filter(
ExcutiveRegistration__user=self.request.user
).only('Covering_Pincode')
]
return Customer.objects.filter(Pincode__in=pincodes,Status='Avaiable')
views.py
class Excutivehomepagess(generics.ListAPIView):
model=Customer
serializer_class=CustomerSerializer
def get_queryset(self):
pincodes = [
e.Covering_Pincode
for e in ExcutiveRegistrationPincode.objects.filter(
ExcutiveRegistration__user=self.request.user.id
).only('Covering_Pincode')
]
return Customer.objects.filter(Pincode__in=pincodes, Status='Avaiable')
serializers.py
class CustomerSerializer(serializers.ModelSerializer):
class Meta:
model= Customer
fields= '__all__'
i have this order model:
class Order(models.Model):
productType = [
('Document', 'Document'),
('Parcel', 'Parcel'),
('Box', 'Box')
]
serviceType = [
('Home', 'Home delivery'),
('Office', 'Office delivery'),
('Pick up from office', 'Pick up from office'),
]
delivery_StatusType = [
('Return', 'Return'),
('Delivering', 'Delivering'),
('Pending', 'Pending'),
('Complete', 'Complete')
]
statustype = [
('Paid', 'Paid'),
('Cash on delivery', 'Cash on delivery')
]
status = [
('Instant', 'Instant'),
('Same Day', 'Same Day'),
('Others', 'Others')
]
payment_types = [
('Cash', 'Cash'),
('Wallet', 'Wallet'),
('Online', 'Online')
]
CHOICE_AREA = [
('Inside Dhaka', 'Inside Dhaka'),
('Dhaka Suburb', 'Dhaka Suburb'),
('Outside Dhaka', 'Outside Dhaka')
]
user = models.ForeignKey(User, on_delete=models.CASCADE)
receiver = models.CharField(max_length=100, blank=False, unique=False)
receiver_Contact = models.CharField(
max_length=20, blank=False, unique=False)
receiver_Email = models.CharField(
max_length=100, blank=False, unique=False)
payment = models.CharField(
max_length=100, choices=payment_types, blank=False)
area = models.CharField(
max_length=100, choices=CHOICE_AREA, blank=True, null=True)
weight = models.CharField(max_length=100, blank=True, null=True)
service = models.CharField(choices=serviceType, max_length=100)
product_Type = models.CharField(choices=productType, max_length=100)
contents = models.CharField(max_length=100, blank=False, unique=False)
quantity = models.CharField(max_length=100, blank=False, unique=False)
package = models.ForeignKey(
Package, on_delete=models.CASCADE, default=0)
priority = models.CharField(
choices=status, blank=True, null=True, max_length=20)
amount = models.CharField(max_length=100, blank=True, unique=False)
delivery_Status = models.CharField(
choices=delivery_StatusType, blank=True, null=True, max_length=50)
paid = models.BooleanField(default=False)
reference_id = models.CharField(max_length=100, blank=True, unique=True)
delivery_time = models.DateField(blank=True, null=True)
created = models.DateField(auto_now_add=True)
tran_id = models.CharField(max_length=20, blank=True, null=True)
driver = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='driver', blank=True, null=True)
driver_amount = models.CharField(max_length=5, blank=False, default='0')
delivery_now = models.DateField(auto_now_add=True)
delivery_later = models.DateField(blank=True, null=True)
accept = models.BooleanField(default=False)
start = models.BooleanField(blank=True, null=True)
finish = models.BooleanField(blank=True, null=True)
pick_up_latitude = models.CharField(blank=True, null=True, max_length=50)
pick_up_longitude = models.CharField(blank=True, null=True, max_length=50)
delivery_latitude = models.CharField(blank=True, null=True, max_length=50)
delivery_longitude = models.CharField(blank=True, null=True, max_length=50)
otp = models.CharField(max_length=10, blank=True, null=True)
pickup_finish = models.BooleanField(default=False)
approve_change_delivery_address = models.BooleanField(
blank=True, null=True, default=False)
confirm_change_delivery_address = models.BooleanField(
blank=True, null=True, default=False)
def __str__(self):
return self.user.username
user model:
class User(AbstractUser):
CITIES = [
('Dhaka','Dhaka'),
('Rajshahi','Rajshahi'),
('Chittagong','Chittagong'),
('Sylhet','Sylhet'),
('Khulna','Khulna'),
('Mymensingh','Mymensingh'),
('Rangpur','Rangpur'),
('Dinajpur','Dinajpur'),
]
Vehicle_type = [
('Truck','Truck'),
('Van','Van'),
('Bike','Bike')
]
email = models.EmailField(unique=True)
contact = models.CharField(null=False,blank=False,max_length=20)
contact2 = models.CharField(null=True,blank=True,max_length=20)
contact3 = models.CharField(null=True,blank=True,max_length=20)
contact4 = models.CharField(null=True,blank=True,max_length=20)
address = models.CharField(null=False,blank=False,max_length=100)
address2 = models.CharField(null=True,blank=True,max_length=100)
postal_code = models.CharField(null=True,blank=True,max_length=10)
city = models.CharField(max_length=30,choices=CITIES)
username = models.CharField(max_length=200,unique=True)
user_pic = models.ImageField(upload_to='media/images/')
n_id = models.CharField(max_length=100)
quote = models.CharField(max_length=250,blank=True,null=True,default='Bio Here. . .')
driving_license = models.ImageField(upload_to='media/documents/')
vehicle_type = models.CharField(max_length=30,choices=Vehicle_type)
vehicle_no = models.CharField(max_length=50)
latitude = models.CharField(max_length=100,default=0)
longitude = models.CharField(max_length=100,default=0)
is_driver = models.BooleanField(default=False)
is_delivery_man = models.BooleanField(default=False)
is_merchant = models.BooleanField(default=False)
is_agent = models.BooleanField(default=False)
is_user = models.BooleanField(default=False)
is_available = models.BooleanField(default=False)
def __str__(self):
return self.username
now the problem is i want to show the username , total amount collections and total orders by individual users(is_agent).no name will be repeated twice though the queryset can have multiple orders agains a user.
i just want to show a users orders total amount and total deliveries in a table row,then other row will be for other users. N.B.filtering (delivery_status="Complete")
update:
agents = User.objects.filter(is_active=True,is_agent=True)
for agent in agents:
agent_id = agent.id
all_orders = Order.objects.filter(user_id = agent_id, delivery_Status="Pending", delivery_time__month = date,
delivery_time__year = year)
now in here i want every agents total delivery count and total amount collected from them but not like showing same user's all querysets but instead i want only by his name will appear once in the table and all deliveries total amount and total deliveries into that row just like the given table
itried this but this has no track of which collection is for whom
individual_orders = []
final_list = []
grand_final_list = []
order_amount = []
individual_orders_count = []
agents = User.objects.filter(is_active=True,is_agent=True)
for agent in agents:
agent_id = agent.id
all_orders = Order.objects.filter(user_id = agent_id, delivery_Status="Pending", delivery_time__month = date,
delivery_time__year = year)
if all_orders:
individual_orders.append(all_orders)
individual_orders_count.append(len(all_orders))
cash_collection = Order.objects.filter(user_id = agent_id, delivery_Status="Pending", delivery_time__month = date,
delivery_time__year = year).values('amount').aggregate(Sum('amount'))
for k,v in cash_collection.items():
if v:
order_amount.append(v)
for query in individual_orders:
for entry in query:
final_list.append(entry.user.username)
grand_final_list = list(dict.fromkeys(final_list))
this table
maybe this helps you?
all_orders = Order.objects.filter(user_id = agent_id, delivery_Status="Pending", delivery_time__month = date,
delivery_time__year = year).values(id, username=F(user__username)).annotate(total_amount = Sum('amount')).annotate(total_deliveries = Count('id))
finally i found a way i am showing the demo here
def driver_deliveries(request):
name = {}
data = []
count = Order.objects.filter(driver__is_driver=True).distinct()
for i in count:
query = Order.objects.filter(driver_id=i.driver.id,delivery_Status="Complete").count()
name[i.driver.username] = data
data.append(query)
data = []
print(name)
for k,v in name.items():
print(k)
for i in v:
print(i)
return render(request,'user/driver_deliveries.html',{'name': name})
I have followed this tutorial to implement inlneformset.
CreateView works (data is registered in database) but UpdateView doesn't.
UpdateView is correctly displayed with correct data.
But it seems like subform (application inlineformset) is never valid and I don't understand why?
forms.py:
NAME = Thesaurus.options_list(2,'fr')
ACCESS = Thesaurus.options_list(3,'fr')
ApplicationFormset = inlineformset_factory(
Utilisateur, Application,
fields=('app_app_nom','app_dro'),
widgets={
'app_app_nom': forms.Select(choices=NAME),
'app_dro': forms.Select(choices=ACCESS)
},
extra=3,
can_delete=True,
)
models.py:
class Projet(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
pro_ide = models.AutoField(primary_key = True)
pro_nom = models.IntegerField("Nom du projet", null=True, blank=True)
pro_log = models.CharField("Log utiisateur", max_length=20, null=True, blank=True)
pro_dat = models.DateTimeField("Date log",auto_now_add=True)
pro_act = models.IntegerField("Projet en cours ?", null=True, blank=True)
log = HistoricalRecords()
class Meta:
db_table = 'tbl_pro'
verbose_name_plural = 'Projets'
ordering = ['pro_ide']
permissions = [
('can_add_project','Can add project'),
]
class Utilisateur(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
uti_ide = models.AutoField(primary_key = True)
pro_ide = models.ForeignKey(Projet, on_delete = models.CASCADE) # related project
uti_nom = models.CharField("Nom", max_length=20, null=True, blank=True)
uti_pre = models.CharField("Prénom", max_length=20, null=True, blank=True)
uti_mai = models.CharField("Email", max_length=40, null=True, blank=True)
uti_sit = models.CharField("Equipe", max_length=20, null=True, blank=True)
uti_pro = models.CharField("Fonction/profil", max_length=200, null=True, blank=True)
uti_dem_dat = models.DateTimeField("Date demande",auto_now_add=True, null=True, blank=True)
uti_val = models.IntegerField("Demande validée ?", null=True, blank=True)
uti_val_dat = models.DateTimeField("Date validation",auto_now_add=True, null=True, blank=True)
uti_log = models.CharField("Log utilisateur", max_length=20, null=True, blank=True)
uti_dat = models.DateTimeField("Date log",auto_now_add=True, null=True, blank=True)
log = HistoricalRecords()
#classmethod
def options_list(cls,pro_ide):
projet = Projet.objects.get(pro_ide=pro_ide)
utilisateurs = Utilisateur.objects.filter(pro_ide=projet.pro_ide)
the_opts_list = [(utilisateur.uti_ide, utilisateur.uti_nom+', '+utilisateur.uti_pre) for utilisateur in utilisateurs]
the_opts_list.insert(0, (None, ''))
return the_opts_list
class Meta:
db_table = 'tbl_uti'
verbose_name_plural = 'Utilisateurs'
ordering = ['uti_ide']
class Application(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
app_ide = models.AutoField(primary_key = True)
uti_ide = models.ForeignKey(Utilisateur, on_delete = models.CASCADE) # related utilisateur
app_app_nom = models.IntegerField("Nom application", null=True, blank=True)
app_dro = models.IntegerField("Droit sur application", null=True, blank=True)
app_sta = models.IntegerField("Statut (création/Modification/Suppression", null=True, blank=True)
app_log = models.CharField("Log utilisateur", max_length=20, null=True, blank=True)
app_dat = models.DateTimeField("Date log",auto_now_add=True, null=True, blank=True)
log = HistoricalRecords()
class Meta:
db_table = 'tbl_app'
verbose_name_plural = 'Applications'
ordering = ['app_ide']
class Administration(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
adm_ide = models.AutoField(primary_key = True)
app_ide = models.ForeignKey(Application, on_delete = models.CASCADE) # related application
adm_nom = models.CharField("Nom d'utilisateur dans l'application", max_length=20, null=True, blank=True)
adm_dem = models.IntegerField("Demande traitée ?", null=True, blank=True)
adm_dem_dat = models.DateTimeField("Date traitement de la demande",auto_now_add=True)
adm_log = models.CharField("Log utilisateur", max_length=20, null=True, blank=True)
adm_dat = models.DateTimeField("Date log",auto_now_add=True)
log = HistoricalRecords()
class Meta:
db_table = 'tbl_adm'
verbose_name_plural = 'Adminitrations'
ordering = ['adm_ide']
permissions = [
('can_manage_project','Can manage project'),
]
UpdateView:
class UtilisateurUpdateView(UpdateView):
model = Utilisateur
fields = ['uti_nom','uti_pre','uti_mai','uti_sit','uti_pro']
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
if self.request.POST:
data["utilisateur"] = self.request.user.username
data["application"] = ApplicationFormset(self.request.POST, instance=self.object)
else:
data["application"] = ApplicationFormset(instance=self.object)
return data
def form_valid(self, form):
context = self.get_context_data()
application = context["application"]
self.object = form.save()
self.object.save()
if application.is_valid(): # ***** NEVER VALID *****
application.instance = self.object
print('application.instance',application.instance)
application.app_app_nom = application.instance.cleaned_data['app_app_nom']
application.app_dro = application.instance.cleaned_data['app_dro']
application.app_log = context["utilisateur"]
application.uti_ide = 1
application.save()
return super().form_valid(form)
def get_success_url(self):
return reverse("project:index")
I have resolve my problem: I forget to insert form_set id in my html template (app_ide in my case)
'DemoAppProductUpdateDestroySerializer' object has no attribute 'get_image'.
i am getting error on 'DemoAppProductUpdateDestroySerializer' object has no attribute 'get_image'. any help, would be appreciated.
'DemoAppProductUpdateDestroySerializer' object has no attribute
'get_image'
models.py
class Product(models.Model):
title = models.CharField(max_length=30)
slug= models.SlugField(blank=True, null=True)
sku = models.CharField(max_length=30)
description = models.TextField(max_length=200, null=True, blank=True)
instruction = models.TextField(max_length=200, null=True, blank=True)
price = models.DecimalField(decimal_places=2, max_digits= 10,)
discount_price= models.DecimalField(decimal_places=2, max_digits= 10, null=True, blank=True)
brand = models.ForeignKey("Brand", null=True, blank=True, on_delete=models.CASCADE)
waist = models.ForeignKey("Waist", null=True, blank=True, on_delete=models.CASCADE)
occasion = models.ForeignKey("Occasion", null=True, blank=True, on_delete=models.CASCADE)
style = models.ForeignKey("Style", null=True, blank=True, on_delete=models.CASCADE)
neck = models.ForeignKey("Neck", null=True, blank=True, on_delete=models.CASCADE)
fit = models.ForeignKey("Fit", null=True, blank=True, on_delete=models.CASCADE)
pattern_type = models.ForeignKey("Pattern_Type", null=True, blank=True, on_delete=models.CASCADE)
color = models.ForeignKey("Color", null=True, blank=True, on_delete=models.CASCADE)
size = models.ManyToManyField("Size", null=True, blank=True)
sleeve = models.ForeignKey("Sleeve_Length", null=True, blank=True, on_delete=models.CASCADE)
material = models.ForeignKey("Material", null=True, blank=True, on_delete=models.CASCADE)
category = models.ManyToManyField('Category', )
default = models.ForeignKey('Category', related_name='default_category', null=True, blank=True, on_delete=models.CASCADE)
created_on = models.DateTimeField(default=timezone.now)
updated_on = models.DateTimeField(null=True, blank=True)
status = models.BooleanField(default=True)
class Meta:
ordering = ["-id"]
def __str__(self): #def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("product_detail", kwargs={"pk": self.pk})
def get_image_url(self):
img = self.productimage_set.first()
if img:
return img.image.url
return img #None
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = unique_slug_generator(instance)
pre_save.connect(pre_save_post_receiver, sender=Product)
def image_upload_to(instance, filename):
title = instance.product.title
slug = slugify(title)
basename, file_extension = filename.split(".")
new_filename = "%s-%s.%s" %(slug, instance.id, file_extension)
return "products/%s/%s" %(slug, new_filename)
class ProductImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
image = models.ImageField(upload_to=image_upload_to)
created_on = models.DateTimeField(default=timezone.now)
status = models.BooleanField(default=True)
def __unicode__(self):
return self.product.title
views.py
class ProductUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
model = Product
queryset = Product.objects.all()
serializer_class = DemoAppProductUpdateDestroySerializer
permission_classes = [IsAdminUser]
authentication_classes = [BasicAuthentication]
serializers.py
class DemoAppProductUpdateDestroySerializer(serializers.ModelSerializer):
image = serializers.SerializerMethodField()
class Meta:
model = Product
fields=[
"id",
"title",
"slug",
"sku",
"price",
"discount_price",
"image",
]
def get_image(self, obj):
return obj.productimage_set.first().image.url
I have two Django models related by a ManyToManyField relationship. Everything works fine except for the inline add dropdown which lists ugly automatically created object names instead of allowing me to format it. How can I specify that?
Models:
class Job(models.Model):
type = models.CharField(max_length=32, choices=JobChoices)
guid = models.CharField(max_length=32)
title = models.CharField(max_length=256)
started_time = models.DateTimeField()
ended_time = models.DateTimeField(blank=True, null=True)
enabled = models.BooleanField(default=False)
running = models.BooleanField(default=False)
working_job_status = models.CharField(max_length=32, choices=StatusCoices)
working_job_length = models.IntegerField(blank=True, null=True)
working_job_progress = models.IntegerField(blank=True, null=True)
working_job_eta_sec = models.IntegerField(blank=True, null=True)
RepeatUnit = (
('s', 'Second'),
('m', 'Minute'),
('h', 'Hour'),
('d', 'Day'),
('W', 'Week'),
('M', 'Month'),
('Y', 'Year'),
)
class Schedule(models.Model):
title = models.CharField(max_length=128)
job = models.ManyToManyField(Job, blank=True, null=True)
start_time = models.DateTimeField(null=False)
end_time = models.DateTimeField(blank=True, null=True)
repeat_unit = models.CharField(blank=True, null=True, max_length=1, choices=RepeatUnit)
repeat_every = models.IntegerField(blank=True, null=True)
repeat_max_count = models.IntegerField(blank=True, null=True)
def __unicode__(self):
return f'{self.title}'
Admin:
class ScheduleAdmin(admin.ModelAdmin):
list_display = ['id', 'title', 'start_time', 'end_time', 'repeat_unit', 'repeat_every', 'repeat_max_count']
class ScheduleInline(admin.TabularInline):
model = Schedule.job.through
min_num = 0
extra = 0
# fields = ('title', )
verbose_name = "Schedule"
verbose_name_plural = "Schedules"
class JobAdmin(admin.ModelAdmin):
list_display = ['id', 'type', 'guid', 'title', 'started_time', 'ended_time', 'enabled', 'running', 'progress']
inlines = [ScheduleInline,]
admin.site.register(Schedule, ScheduleAdmin)
admin.site.register(Job, JobAdmin)
And, when I click on the inlines drop-down menu I get:
changing from __unicode__(self) to __str__(self) did the trick