django import export error in import xlsx - django

I don't understand why i'm getting this error when I try to insert the xlsx file. This is my model
class Finance(models.Model):
invoiceNumber = models.CharField(blank=False, null=False,
primary_key=True)
student = models.CharField(max_length=50, blank=False, null=False)
rollGroup = models.CharField(max_length=50, blank=False, null=False)
invoiceTo = models.CharField(max_length=50, blank=False, null=False)
dob = models.CharField(max_length=50, null=True)
gender = models.CharField(max_length=50, blank=False, null=False)
status = models.CharField(max_length=50, blank=False, null=False)
schedule = models.CharField(max_length=50,blank=False, null=False)
totalValue = models.CharField(max_length=50, blank=False, null=False)
issueDate = models.CharField(max_length=50, null=True)
dueDate = models.CharField(max_length=50, null=True)
datePaid = models.CharField(max_length=50, null=True)
amountPaid = models.CharField(max_length=50, null=True)
def __str__(self):
return self.invoiceNumber
This is my resource model
class FinanceResource(resources.ModelResource):
invoiceNumber = Field(attribute='invoiceNumber', column_name='Invoice
Number')
student = Field(attribute='student', column_name='Student')
rollGroup = Field(attribute='rollGroup', column_name='Roll Group')
invoiceTo = Field(attribute='invoiceTo', column_name='Invoice To')
dob = Field(attribute='dob', column_name='DOB')
gender = Field(attribute='gender', column_name='Gender')
status = Field(attribute='status', column_name='Status')
schedule = Field(attribute='schedule', column_name='Schedule')
totalValue = Field(attribute='totalValue', column_name='Total
Value(PKR
₨)')
issueDate = Field(attribute='issueDate', column_name='Issue Date')
dueDate = Field(attribute='dueDate', column_name='Due Date')
datePaid = Field(attribute='datePaid', column_name='Date Paid')
amountPaid = Field(attribute='amountPaid', column_name='Amount Paid
(PKR
₨)')
class Meta:
model = Finance
import_id_fields = ('invoiceNumber',)
export_order = ('invoiceNumber', 'student', 'rollGroup',
'invoiceTo', 'dob', 'gender', 'status', 'schedule',
'totalValue', 'issueDate', 'dueDate', 'datePaid',
'amountPaid')
skip_unchanged = True
report_skipped = True
And the error im getting
And when i use the default primary key i get
Line number: 1 - str returned non-string (type int)
2, styles, harry, Spring 2020, Family, None, M, Pending, First Installment, 57000, None, 10/06/2020, None, 0
Traceback (most recent call last):
File "C:\Users\long play computers\PycharmProjects\DotsPrototype\venv\lib\site-packages\import_export\resources.py", line 559, in import_row
row_result.object_repr = force_str(instance)
File "C:\Users\long play computers\PycharmProjects\DotsPrototype\venv\lib\site-packages\django\utils\encoding.py", line 64, in force_str
s = str(s)
TypeError: str returned non-string (type int)

Related

how to show all orders amount respective to every user in a table without duplicating a username twice

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})

Django model is inheriting all super model Fields, except for IntegerField

I'm having a weird issue, I have a models' hierarchy, an abstract User class:
class User(AbstractBaseUser):
user_name = models.CharField(max_length=32, unique=True)
email = models.EmailField(max_length=255, unique=True, null=True)
phone = PhoneNumberField()
access_token = models.CharField(max_length=255, unique=True, null=True)
notifications_token = models.CharField(max_length=255, unique=True, null=True)
photo = models.ImageField(null=True)
person_in_contact = models.CharField(max_length=32, null=True)
active = models.BooleanField(default=False)
confirmedEmail = models.BooleanField(default=False)
confirmedPhone = models.BooleanField(default=False)
completedProfile = models.BooleanField(default=False)
visible = models.BooleanField(default=True)
#property
def is_active(self):
return self.active
# def __str__(self):
# return "Client : " + self.user_name + " Email:" + self.email
def get_email(self):
return self.email
USERNAME_FIELD = 'user_name'
REQUIRED_FIELDS = ['user_name', 'phone', 'password']
class Meta:
abstract = True
then a person class and a company (no issue with this one) class that inherit from this one:
class Person(User):
GENDER = (('F', 'FEMALE'), ('M', 'MALE'))
name = models.CharField(max_length=50, null=True)
surname = models.CharField(max_length=50, null=True)
adress = models.CharField(max_length=255, null=True)
birth_date = models.DateField(null=True)
gender = models.CharField(max_length=1, choices=GENDER, null=True)
age = models.IntegerField(null=True)
def age(self):
today = date.today()
return today.year - self.birth_date.year
# def __str__(self):
# return super().__str__() + " Name : " + self.name
class Meta:
abstract = True
as you can see, the only field that's IntegerField() is the age field.
now i have a Traveller and a Driver classes that inherit from the person class,
the issue is the age field, doesn't show in the database, unless i override it in one of the classes, that's what i did, i override it in traveller so it appeared in the database, but didn't override it in the driver, so it didn't show.
Traveller:
class Traveller(Person):
photo = models.ImageField(null=True, upload_to='travellers/profile_pictures')
age = models.IntegerField(null=True)
class Meta:
verbose_name_plural = 'Travellers'
Driver:
class Driver(Person):
rating = models.DecimalField(default=0, decimal_places=1, max_digits=3)
driving_license = models.CharField(max_length=50, null=True)
insurance_number = models.CharField(max_length=50, null=True)
company = models.ForeignKey(TransportCompany, on_delete=models.DO_NOTHING, null=True)
photo = models.ImageField(null=True, upload_to='drivers/profile_pictures')
i need to know how i can fix this, or what's the issue, any help is appreciated.
The reason this happens is because your age field has the same name as the age function. As a result, the age = ... field is ignored by Python in favor of the age function, since that is the last time you defined the age variable.
For the same reason the age field pops up in sublasses: you defined an age variable over there, and that takes precedence over the "inherited" age method.
You should rename one of the two. For example with:
class Person(User):
GENDER = (('F', 'FEMALE'), ('M', 'MALE'))
name = models.CharField(max_length=50, null=True)
surname = models.CharField(max_length=50, null=True)
adress = models.CharField(max_length=255, null=True)
birth_date = models.DateField(null=True)
gender = models.CharField(max_length=1, choices=GENDER, null=True)
_age = models.IntegerField(null=True)
def age(self):
today = date.today()
bod = self.birth_date
before_dob = (today.month, today.day) < (bod.month, bod.day)
return today.year - self.birth_date.year - before_dob
class Meta:
abstract = True
Note that the calculation of the age was not completely accurate: if we are before the birthday of that year, you need to subtract one from the age.

How can I allow a user to filter models dynamically and export only certain fields?

I've been asked to design a way for people to search through multiple models on criteria they enter and allow them to export any number of fields they select.
Example:
User enters "Teacher" as a term for Job Title and "Google" for a Work Site Location but want to export "Employee ID", "First Name", "Last Name", "Date of Birth"
I'm sure this is possible, but I'm at a complete loss for where to start.
My models (for reference) are here:
import datetime
from django.conf import settings
from django.db import models
from django.db.models import Q
from django.utils import timezone
class Classification(models.Model):
name = models.CharField(max_length=255, blank=False, null=False, verbose_name='Classification Name')
def __str__(self):
return '{}'.format(self.name)
class Meta:
db_table = 'Classification'
verbose_name = 'Classification'
verbose_name_plural = 'Classifications'
class Location(models.Model):
name = models.CharField(max_length=255, blank=False, null=False, verbose_name='Name')
aeries_id = models.CharField(max_length=25, blank=True, null=True, verbose_name='Aeries ID')
county_id = models.CharField(max_length=25, blank=True, null=True, verbose_name='County ID')
def __str__(self):
return '{}'.format(self.name)
class Meta:
db_table = 'Location'
verbose_name = 'Location'
verbose_name_plural = 'Locations'
ordering = ['name']
class Person(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True)
current_identity = models.ForeignKey('PersonIdentity', blank=True, null=True, on_delete=models.SET_NULL, verbose_name='Current Identity', related_name='current_identity')
employee_id = models.CharField(max_length=255, null=False, blank=False, verbose_name='Employee ID')
birthdate = models.DateField(blank=True, null=True, verbose_name='Birthdate')
original_hire_date = models.DateField(blank=True, null=True, verbose_name='Original Hire Date')
def __str__(self):
if self.current_identity is not None:
return '{}'.format(str(self.current_identity))
else:
return "{}".format(self.employee_id)
#property
def current_age(self):
from dateutil.relativedelta import relativedelta
difference_in_years = relativedelta(timezone.now().date(), self.birthdate).years
return difference_in_years
def primary_assignment(self):
return self.jobassignment_set.filter(Q(end_date__gte=timezone.now()) | Q(end_date=None)).order_by('priority')[0]
#property
def display_name(self):
if self.current_identity:
return '{0.first_name} {0.last_name} ({1.employee_id})'.format(self.current_identity, self)
else:
return 'Employee ID {0.employee_id}'.format(self)
#property
def is_certificated(self):
assignments = JobAssignment.objects.filter(Q(end_date__gte=timezone.now()) | Q(end_date=None)).filter(
person=self,
classification__name__icontains="Certificated"
)
return assignments.count() >= 1
class Meta:
db_table = 'Person'
verbose_name = 'Person'
verbose_name_plural = 'People'
class PersonIdentity(models.Model):
person = models.ForeignKey(Person, verbose_name='Person', on_delete=models.CASCADE)
first_name = models.CharField(max_length=50, blank=True, null=True, verbose_name='First Name')
middle_name = models.CharField(max_length=50, blank=True, null=True, verbose_name='Middle Name')
last_name = models.CharField(max_length=50, blank=True, null=True, verbose_name='Last Name')
start_date = models.DateField(blank=False, null=False, default=datetime.date.today, verbose_name='Start Date')
end_date = models.DateField(blank=True, null=True, verbose_name='End Date')
def __str__(self):
first_name = '' if self.first_name is None else self.first_name
last_name = '' if self.last_name is None else self.last_name
if self.middle_name is not None and self.middle_name != '':
return "{} {}. {} ({})".format(first_name, self.middle_name[0], last_name, self.person.employee_id)
else:
return "{} {} ({})".format(first_name, last_name, self.person.employee_id)
def save(self, *args, **kwargs):
change_identity = False
if not self.id:
change_identity = True
super().save(*args, **kwargs)
if change_identity:
self.person.current_identity = self
self.person.save()
class Meta:
db_table = 'PersonIdentity'
verbose_name = 'Person Identity'
verbose_name_plural = 'Person Identities'
ordering = ['end_date', 'last_name', 'first_name']
class Contact(models.Model):
person = models.OneToOneField(Person, on_delete=models.CASCADE, verbose_name='Person')
email_address = models.EmailField(blank=True, null=True, verbose_name='Primary Email')
phone_number = models.CharField(max_length=15, blank=True, null=True, verbose_name='Phone Number')
phone_extension = models.CharField(max_length=255, blank=True, null=True, verbose_name='Phone Extension')
address1 = models.CharField(max_length=255, blank=True, null=True, verbose_name='Address 1')
address2 = models.CharField(max_length=255, blank=True, null=True, verbose_name='Address 2')
city = models.CharField(max_length=255, blank=True, null=True, verbose_name='City')
state = models.CharField(max_length=2, default='CA', blank=True, null=True, verbose_name='State')
postal = models.CharField(max_length=5, blank=True, null=True, verbose_name='Postal Code')
def __str__(self):
return '{}'.format(self.person.current_identity)
class Meta:
db_table = 'Contact'
verbose_name = 'Contact'
verbose_name_plural = 'Contacts'
class Department(models.Model):
department_id = models.CharField(max_length=5, blank=False, null=False, verbose_name='Department ID')
description = models.CharField(max_length=255, blank=False, null=False, verbose_name='Department Description')
def __str__(self):
return '{}'.format(self.description)
class Meta:
db_table = 'Department'
verbose_name = 'Department'
verbose_name_plural = 'Departments'
class Job(models.Model):
name = models.CharField(max_length=255, blank=False, null=False, verbose_name='Name')
code = models.CharField(max_length=255, blank=False, null=False, verbose_name='Code')
def __str__(self):
return '{}'.format(self.name)
class Meta:
db_table = 'Job'
verbose_name = 'Job'
verbose_name_plural = 'Jobs'
class JobPosition(models.Model):
job = models.ForeignKey(Job, blank=True, null=True, verbose_name='Job')
reports_to = models.ForeignKey('JobPosition', blank=True, null=True, verbose_name='Reports To')
name = models.CharField(max_length=255, blank=True, null=True, verbose_name='Name')
number = models.CharField(max_length=255, blank=False, null=False, verbose_name='Number')
def __str__(self):
return '{}'.format(self.name)
class Meta:
db_table = 'JobPosition'
verbose_name = 'Job Position'
verbose_name_plural = 'Job Positions'
class JobAssignment(models.Model):
person = models.ForeignKey(Person, blank=False, null=False, verbose_name='Person')
position = models.ForeignKey(JobPosition, blank=False, null=False, verbose_name='Position')
location = models.ForeignKey(Location, blank=True, null=True, verbose_name='School')
classification = models.ForeignKey(Classification, blank=True, null=True, verbose_name='Classification')
start_date = models.DateField(blank=True, null=True, verbose_name='Start Date')
end_date = models.DateField(blank=True, null=True, verbose_name='End Date')
effective_date = models.DateField(blank=True, null=True, verbose_name='Effective Date')
fte = models.CharField(max_length=10, blank=True, null=True, verbose_name='FTE')
seniority_date = models.DateField(blank=True, null=True, verbose_name='Seniority Date')
last_start_date = models.DateField(blank=True, null=True, verbose_name='Last Start Date')
last_pay_date = models.DateField(blank=True, null=True, verbose_name='Last Pay Date')
entry_date = models.DateField(blank=True, null=True, verbose_name='Position Entry Date')
record_number = models.IntegerField(default=0, verbose_name='Position Record Number')
pay_group = models.CharField(max_length=3, blank=True, null=True, verbose_name='Pay Group')
indicator = models.CharField(max_length=1, blank=True, null=True, verbose_name='Indicator')
full_or_part_time = models.CharField(max_length=1, blank=True, null=True, verbose_name='Full/Part')
standard_hours_per_week = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True, verbose_name='Standard Hours per Week')
pay_status = models.CharField(max_length=1, blank=True, null=True, verbose_name='Pay Status')
comp_rate = models.DecimalField(max_digits=15, decimal_places=6, blank=True, null=True, verbose_name='Comp Rate')
comp_frequency = models.CharField(max_length=10, blank=True, null=True, verbose_name='Comp Freq')
hourly_rate = models.DecimalField(max_digits=10, decimal_places=6, blank=True, null=True, verbose_name='Hrly Rate')
daily_rate = models.DecimalField(max_digits=10, decimal_places=6, blank=True, null=True, verbose_name='Daily Rt')
rate_code = models.CharField(max_length=10, blank=True, null=True, verbose_name='Rate Code')
compensation_rate = models.DecimalField(max_digits=15, decimal_places=6, blank=True, null=True, verbose_name='Compensation Rate')
total_cdays = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True, verbose_name='TOTAL_CDAYS')
teacher_hours = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True, verbose_name='Teacher Hours')
def __str__(self):
return '{} - {}'.format(self.position.name, self.position.number)
#classmethod
def current_assignments(cls):
return cls.objects.filter(Q(end_date__gte=timezone.now()) | Q(end_date=None)).exclude(person__ssn__isnull=True).exclude(person__current_identity__isnull=True).exclude(person__contact__isnull=True)
class Meta:
db_table = 'JobAssignment'
verbose_name = 'Job Assignment'
verbose_name_plural = 'Job Assignments'
ordering = ['location__name', 'person__current_identity__last_name', 'person__current_identity__first_name', 'position__name']

Django - edit many-to-many inline

I have following model
class Day(models.Model):
date = models.DateField(auto_now=False, auto_now_add=False)
price = models.FloatField()
payment_method = models.CharField(max_length = 200, blank=True)
payment_date = models.CharField(max_length=200, blank=True)
room = models.ForeignKey(Room, null=True, blank=True, verbose_name='Номер', on_delete=models.CASCADE)
def __unicode__(self):
return str(self.date)
class Reservation(models.Model):
start = models.DateField(verbose_name='Заезд', auto_now=False, auto_now_add=False, blank=False)
end = models.DateField(verbose_name='Выезд', auto_now=False, auto_now_add=False, blank=False)
check_in_time = models.TimeField(verbose_name='Время заезда', blank=False)
check_out_time = models.TimeField(verbose_name='Время выезда', blank=False)
has_refund = models.BooleanField(verbose_name='Возвратная бронь', default=True)
payed = models.BooleanField(verbose_name='Оплачено', default=False)
reserved_days = models.ManyToManyField(Day, blank=False)
additional_services = models.ManyToManyField(AdditionalService)
guest_name = models.CharField(verbose_name='Имя гостя', max_length=200, blank=True)
reservation_number = models.CharField(verbose_name='Номер брони', max_length=200, blank=True)
What I want is to have ability to edit Day on Reservation page
I try the following as in the django docs
class ReservedDaysInline(admin.TabularInline):
model = Reservation
extra = 1
class ReservationAdmin(admin.ModelAdmin):
inlines = (ReservedDaysInline,)
class DayAdmin(admin.ModelAdmin):
inline = (ReservedDaysInline,)
admin.site.register(Reservation, ReservationAdmin)
admin.site.register(Day, DayAdmin)
But it doesnt work.
What am I doing wrong ?
Try this from doc
class ReservedDaysInline(admin.TabularInline):
model = Reservation.reserved_days.through
extra = 1
class ReservationAdmin(admin.ModelAdmin):
inlines = (ReservedDaysInline,)
exclude = ('reserved_days',)

Using django modelform for 2 instances not saving correctly

In Django 1.6.1 I have a vehicle model which might zero or up to 2 traded-in units. Every time I edit any record, whether the change is trade-in instance #1 or instance 2, both records are updated with values instance #2.
Vehicle model:
class Vehicle(models.Model):
stock = models.CharField(max_length=10, blank=False, db_index=True)
vin = models.CharField(max_length=17, blank=False, db_index=True)
#vinlast8 = models.CharField(max_length=8, blank=False, db_index=True)
make = models.CharField(max_length=15, blank=False)
model = models.CharField(max_length=15, blank=False)
year = models.CharField(max_length=4, blank=False)
registry = models.IntegerField(blank=True, verbose_name='Reg #', null=True)
plate = models.CharField(blank=True, null=True, max_length=10)
tagno = models.IntegerField(blank=True, null=True, verbose_name='Tag #')
tag_exp = models.DateField(blank=True, null=True, verbose_name='Tag Exp')
Tradein model:
class TradeIn(Vehicle):
TradeInVehicle = (
(1, 'First vehicle'),
(2, 'Second vehicle'),
)
vehicle_sale = models.ForeignKey(VehicleSale)
tradeinpos = models.IntegerField(choices=TradeInVehicle)
lienholder = models.CharField(max_length=15, blank=True, null=True, verbose_name='L/holder')
lhdocrequested = models.DateField(blank=True, null=True, verbose_name='D/Requested')
lhdocreceived = models.DateField(blank=True, null=True, verbose_name='D/Received')
class Meta:
db_table = 'tradein'
def __unicode__(self):
return self.stock
def save(self, *args, **kwargs):
self.stock = self.stock.upper()
self.vin = self.vin.upper()
return super(TradeIn, self).save(*args, **kwargs)
The related sections on view is:
These sections are related to request.GET
current_vehicle = VehicleSale.objects.get(pk=pk)
tradeIns = current_vehicle.tradein_set.all().order_by('tradeinpos')
# Also add tradein_form to t_data so it can be rendered in the template
t_count = tradeIns.count()
if t_count == 0:
t_data['tradein1_form'] = TradeInForm()
t_data['tradein2_form'] = TradeInForm()
if t_count >= 1 and tradeIns[0] and tradeIns[0].tradeinpos == 1:
t_data['tradein1_form'] = TradeInForm(instance=tradeIns[0])
t_data['tradein2_form'] = TradeInForm()
if t_count == 2 and tradeIns[1] and tradeIns[1].tradeinpos == 2:
t_data['tradein2_form'] = TradeInForm(instance=tradeIns[1])
Now these are related to request.POST:
if 'tradein-form' in request.POST:
if tradeIns.count() > 0:
if tradeIns[0]:
tradein1_form = TradeInForm(request.POST, instance=tradeIns[0])
if tradein1_form.is_valid():
tradein1_form.save()
if tradeIns[1]:
tradein2_form = TradeInForm(request.POST, instance=tradeIns[1])
if tradein2_form.is_valid():
tradein2_form.save()
While reviewing contents of request.POST, it does contain any change I make in either instance. But always, the 2nd instance is saved.
What am I missing or have wrong?