Здравствуйте, есть модель групп "StudentsGroup" и есть прикрепленный к нему путем "inlines" модель "Rooms".
Хотел реализовать валидацию форм в админке в модели "StudentsGroup". Умею делать валидацию с данными "StudentsGroup", но никак не могу получить доступ к данным "Rooms".
Пожалуйста помогите. Спасибо.
В классе SGAdminForm нужно
newrooms = Rooms.objects.filter(name__name=group_name)
поменять типа на cleaned_data["ROOMS как то нужно вывести"] из inlines и провести валидацию.
В данный момент все исправно работает если заранее сохранить РУМС и только потом заливать студентов и проверять на отсутствие коллизий. Но хотелось бы это делать параллельно и правильно))
class SGAdminForm(forms.ModelForm):
class Meta:
model = StudentsGroup
fields = '__all__'
def clean_students(self):
students = self.cleaned_data['students']
group_name = self.cleaned_data['name']
newrooms = Rooms.objects.filter(name__name=group_name)
errors=[]
for student in students:
groups = StudentsGroup.objects.filter(students=student).exclude(name=group_name)
for group in groups:
rooms = Rooms.objects.filter(name=group)
for room in rooms:
for newroom in newrooms:
if newroom.room == room.room:
if newroom.dayOfTheWeek == room.dayOfTheWeek:
old = datetime.datetime.now()
new = datetime.datetime.now()
oldtime = datetime.time(room.time.hour, room.time.minute)
newtime = datetime.time(newroom.time.hour, newroom.time.minute)
rold = old.replace(hour=oldtime.hour, minute=oldtime.minute, second=0, microsecond=0)
rnew = new.replace(hour=newtime.hour, minute=newtime.minute, second=0, microsecond=0)
nptimeold = nptime(rold.hour,rold.minute)
nptimenew = nptime(rnew.hour,rnew.minute)
if rold >= rnew:
if (nptimeold-nptimenew)<timedelta(minutes=int(newroom.duration)):
errors.append(str("Student "+str(student.username)+" uzhe est v gruppe "+str(group.id)+"#"+str(translit(smart_unicode(group.name), "ru",reversed=True)+" -den nedeli="+str(smart_unicode(room.dayOfTheWeek))+" -"+str(translit(smart_unicode(room.get_room_display()),"ru",reversed=True))+" -vremya "+str(room.time))))
else:
if (nptimenew-nptimeold)<timedelta(minutes=int(room.duration)):
errors.append(str("Student "+str(student.username)+" uzhe est v gruppe "+str(group.id)+"#"+str(translit(smart_unicode(group.name), "ru",reversed=True)+" -den nedeli="+str(smart_unicode(room.dayOfTheWeek))+" -"+str(translit(smart_unicode(room.get_room_display()),"ru",reversed=True))+" -vremya "+str(room.time))))
if errors:
raise forms.ValidationError(errors)
return students
class ChoiceInline4(admin.TabularInline):#admin.StackedInline):
model = Rooms
extra = 0
max_num = 7
min_num = 0
class GroupAdmin(admin.ModelAdmin):
form = SGAdminForm
list_display = ('name','teacher','created','course','price','number_of_lessons')
filter_horizontal = ('students','finished')
list_filter = ('course','teacher')
fieldsets = [
(None, {'fields': ['name','teacher','description']}),
('Additional', {'fields': ['course','price','number_of_lessons']}),
('Date information', {'fields': ['created','start','ended'], 'classes': ['collapse']}),
('List of Students', {'fields': ['students']}),
('Finished students info', {'fields': ['finished'], 'classes': ['collapse']}),
]
search_fields=['name','teacher__first_name','teacher__last_name']
inlines = [ChoiceInline4]