Y
Y
Yeldos Adetbekov2016-11-02 20:01:26
Django
Yeldos Adetbekov, 2016-11-02 20:01:26

How to get data from cleaned_data "inlines"?

Hello, there is a "StudentsGroup" model of groups and there is a "Rooms" model attached to it by "inlines".
I wanted to implement form validation in the admin panel in the "StudentsGroup" model. I can do validation with "StudentsGroup" data, but I can't get access to "Rooms" data in any way.
Please, help. Thank you.
In the SGAdminForm class, you need

newrooms = Rooms.objects.filter(name__name=group_name)

change the type to cleaned_data["ROOMS somehow needs to be removed"] from inlines and validate.
At the moment, everything is working properly if you save the RUMS in advance and only then fill in the students and check for the absence of collisions. But I would like to do it in parallel and correctly))
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]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2016-11-03
@sergey-gornostaev

Define a formset for inline and do validation in it:

class RoomsInlineFormset(forms.models.BaseInlineFormSet):
    def clean(self):
        count = 0
        for form in self.forms:
            if hasattr(form, 'cleaned_data'):
                    count += 1
        if count < 1:
            raise forms.ValidationError(u'Не присвоена комната')

class ChoiceInline4(admin.TabularInline):
    model = Rooms    
    formset = RoomsInlineFormset

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question