Backwards in the relationship chain?
I have spent hours trying to find the answer to this. What makes it even more frustrating is that I'm new to django development and not a real programmer by trade (I am a UNIX admin) so I am struggling to label what I am trying to do so that I can search for an answer. Here's what I have: In my models.py file I have the following class definitions: class Family(models.Model): ... FamilyID = models.AutoField(primary_key=True) Name = models.CharField(verbose_name="Family Name") class FamilyMember(AbstractUser): ID = models.AutoField(primary_key=True) FamilyID = models.ForeignKey(Family, blank=True, null=True) ... class Teacher(models.Model): ... TeacherID = models.AutoField(primary_key=True) ID = models.OneToOneField(FamilyMember) ... class CourseCatalog(models.Model): ... TeacherID = models.ForeignKey(Teacher, blank=True, null=True) ... So, there is a table called Family that I belong to. It holds my family name and a couple of other fields. There is then a one-to-many relationship from that to the FamilyMember table. In this table I have a record for each member of my family. The FamilyMember table is also being used as the authentication table for my site. I have not replaced the default security model but only abstracted it and added additional fields. I am a teacher so there is also a record in the Teacher table. This table contains the FamilyMember.ID field. That's the setup for me. My main information is in the FamilyMember table and my FamilyMember.ID field is stored in the Family and the Teacher tables. On to the list of classes... There is a table called CourseCatalog that contains information about a class that I will teach. One of the columns is called TeacherID and this stores the TeacherID from the Teacher table. I set it up this way so that an admin can add a class and then assign it only to a teacher. The drop down list should not include FamilyMembers that are not teachers. Here are my questions and problems: - I want to log into the website as myself and modify only my classes. It would also be OK to modify the classes of everyone in my family. Either solution would be fine. However, I can't figure out how to do either of these things. - It seems to me that what I'm doing is trying to go backwards in the relationship chain. I have my CourseCatalog record that includes the TeacherID. I need to look that ID up in the Teacher table to get the FamilyMember.ID. I then need to use that to look up the record in the FamilyMember table. Once I have that, I can get the username and compare it to the username of the logged in user (me). Finally, I can filter on records where these two match. - I'm wondering if I have architected my database wrong. Is there an easier way to do this? Maybe I should get rid of the Teacher table and just use a boolean for teacher in the FamilyMember table. The concern that I have with this is when I start working on the Student table. I need to store more information about a student (allergy, emergency contacts, etc) and don't think it is appropriate to add those fields to the FamilyMember table because they are only used for students. - I'm asking for you experts to help guide me through this. Any advice is greatly appreciated. -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. For more options, visit https://groups.google.com/groups/opt_out.
Re: Backwards in the relationship chain?
Thank you so much for the reply and help. I am not stuck with this database format and can change it as necessary. I will modify it as you suggested (let Django create the primary key, remove the ID suffix from the column names, etc.). I will then look for the managers as you suggested. I did find a solution to what I was trying doing. I was reading through the Python documentation and then through the Django documentation (for the up-teenth time) and discovered that I can "move backward" through the relationship chain easily (I'm still not sure what the proper phrase is for what I'm trying to do). For example, I can display the Family.Name by simply doing something like this: {{ object.TeacherID.ID.FamilyID }} So, now I can do something like this: {% if user.FamilyID = object.TeacherID.ID.FamilyID %} Or, after making the changes that you suggested I can do this (and use the actual ID numbers for comparison) {% if user.Family.ID = object.Teacher.ID.Family.ID %} Thank you again for the information that you provided. It will greatly help me move forward from here. -Chris On Wednesday, July 24, 2013 2:51:43 PM UTC-4, ke1g wrote: > > First, is this a pre-existing data base whose format you are stuck with? > > While your models probably can be made to work, it is more common to let > Django take care of creating a single primary key in a model (called "id" > (lower case) by default). > > Also, while ForeignKey fields are implemented by storing the primary key > value of the desired row in the other table, that, too, is intended to be > hidden, so when you make a reference through a ForeignKey field, the ORM > actually hands you an instance of the foreign Model, not the id. That is: > > instanceOfCourseCatalog.TeacherID > > is an instance of Teacher, not the TeacherID of a teacher. To get the id > integer, for those very rare cases in which it is valuable, you woudl use: > > instanceOfCourseCatalog.TeacherID.TeacherID > > If you go the normal way and let Django create the primary key fields by > the default name "id", and if, to better describe what is happening, > removed the "ID from the end of your ForeignKey field names and, also a > convention, made them lowercase, the lines above lines would become, > respectively: > >instanceOfCourseCatalog.teacher > > and > >instanceOfCourseCatalog.teacher.id > > In this case Django would have added a "manager" to the Teacher model > called "coursecatalog_set" (or just possibly "course_catalog_set", not > certain and don't have time to search the documents now), but whose name > your can specify with the "related_name" argument to the ForeignKey field. > This manager has all the usual queryset methods, so you can append ".all()' > to get an array of all the CourseCatalog objects with that Teacher. See > https://docs.djangoproject.com/en/1.5/topics/db/queries/#backwards-related-objects > > Bill > > > On Wed, Jul 24, 2013 at 8:37 AM, Chris Ryan > > > wrote: > >> I have spent hours trying to find the answer to this. What makes it even >> more frustrating is that I'm new to django development and not a real >> programmer by trade (I am a UNIX admin) so I am struggling to label what I >> am trying to do so that I can search for an answer. >> >> >> Here's what I have: >> >> >> In my models.py file I have the following class definitions: >> >> >> class Family(models.Model): >> >> ... >> >> FamilyID = models.AutoField(primary_key=True) >> >> Name = models.CharField(verbose_name="Family Name") >> >> >> >> >> >> >> class FamilyMember(AbstractUser): >> >> >> >> ID = models.AutoField(primary_key=True) >> >> FamilyID = models.ForeignKey(Family, blank=True, null=True) >> >> ... >> >> >> >> >> >> class Teacher(models.Model): >> >> ... >> >> TeacherID = models.AutoField(primary_key=True) >> >> ID = models.OneToOneField(FamilyMember) >> >> ... >> >> >> >> >> >> >> class CourseCatalog(models.Model): >> >> ... >> >> TeacherID = models.ForeignKey(Teacher, blank=True, null=True) >> >> ... >> >> >> --
Re: Backwards in the relationship chain?
Sorry. I should have typed the ID as lower case id in {% if user.Family. <http://user.family.id/>id = object.Teacher.id.Family.<http://object.teacher.id.family.id/> id %} On Wednesday, July 24, 2013 3:28:52 PM UTC-4, Chris Ryan wrote: > > Thank you so much for the reply and help. I am not stuck with this > database format and can change it as necessary. I will modify it as you > suggested (let Django create the primary key, remove the ID suffix from the > column names, etc.). I will then look for the managers as you suggested. > > I did find a solution to what I was trying doing. I was reading through > the Python documentation and then through the Django documentation (for the > up-teenth time) and discovered that I can "move backward" through the > relationship chain easily (I'm still not sure what the proper phrase is for > what I'm trying to do). For example, I can display the Family.Name by > simply doing something like this: > > {{ object.TeacherID.ID.FamilyID }} > > So, now I can do something like this: > > {% if user.FamilyID = object.TeacherID.ID.FamilyID %} > > > Or, after making the changes that you suggested I can do this (and use the > actual ID numbers for comparison) > > {% if user.Family.ID = object.Teacher.ID.Family.ID %} > > Thank you again for the information that you provided. It will greatly > help me move forward from here. > > -Chris > > > > On Wednesday, July 24, 2013 2:51:43 PM UTC-4, ke1g wrote: >> >> First, is this a pre-existing data base whose format you are stuck with? >> >> While your models probably can be made to work, it is more common to let >> Django take care of creating a single primary key in a model (called "id" >> (lower case) by default). >> >> Also, while ForeignKey fields are implemented by storing the primary key >> value of the desired row in the other table, that, too, is intended to be >> hidden, so when you make a reference through a ForeignKey field, the ORM >> actually hands you an instance of the foreign Model, not the id. That is: >> >> instanceOfCourseCatalog.TeacherID >> >> is an instance of Teacher, not the TeacherID of a teacher. To get the id >> integer, for those very rare cases in which it is valuable, you woudl use: >> >> instanceOfCourseCatalog.TeacherID.TeacherID >> >> If you go the normal way and let Django create the primary key fields by >> the default name "id", and if, to better describe what is happening, >> removed the "ID from the end of your ForeignKey field names and, also a >> convention, made them lowercase, the lines above lines would become, >> respectively: >> >>instanceOfCourseCatalog.teacher >> >> and >> >>instanceOfCourseCatalog.teacher.id >> >> In this case Django would have added a "manager" to the Teacher model >> called "coursecatalog_set" (or just possibly "course_catalog_set", not >> certain and don't have time to search the documents now), but whose name >> your can specify with the "related_name" argument to the ForeignKey field. >> This manager has all the usual queryset methods, so you can append ".all()' >> to get an array of all the CourseCatalog objects with that Teacher. See >> https://docs.djangoproject.com/en/1.5/topics/db/queries/#backwards-related-objects >> >> Bill >> >> >> On Wed, Jul 24, 2013 at 8:37 AM, Chris Ryan wrote: >> >>> I have spent hours trying to find the answer to this. What makes it even >>> more frustrating is that I'm new to django development and not a real >>> programmer by trade (I am a UNIX admin) so I am struggling to label what I >>> am trying to do so that I can search for an answer. >>> >>> >>> Here's what I have: >>> >>> >>> In my models.py file I have the following class definitions: >>> >>> >>> class Family(models.Model): >>> >>> ... >>> >>> FamilyID = models.AutoField(primary_key=True) >>> >>> Name = models.CharField(verbose_name="Family Name") >>> >>> >>> >>> >>> >>> >>> class FamilyMember(AbstractUser): >>> >>> >>> >>> ID = models.AutoField(primary_key=True) >>> >>> FamilyID = models.ForeignKey(Family, blank=True, null=True) >>> >>
What is the best way to architect this part of the application?
I thank you again for answering a different question a couple of weeks ago. Today, however, I'm struggling with the best way to architect a part of my app. I'm hoping that you can help me figure out the best way to provide the necessary functionality to the user. I am building an application that allows home school families the ability to register their children for upcoming classes. This is a co-operative and so parents can be teachers, admins, etc. and there can be multiple children in each family. You may find the following information familiar. I copied/pasted it from my earlier post. In my models.py file I have the following class definitions: class Family(models.Model): ... name = models.CharField(verbose_name="Family Name") class FamilyMember(AbstractUser): family = models.ForeignKey(Family, blank=True, null=True) family_member_role = models.ForeignKey(FamilyMemberRole, blank=True, null=True)#For our example, let's assume this is either a parent or a child ... class Student(models.Model): ... family_member = models.OneToOneField(FamilyMember) ... class Schedule(models.Model): ... semester = models.ForeignKey(Semester, verbose_name='Semester') student = models.ManyToManyField(Student, verbose_name='Students', blank=True, null=True) ... So, there is a table called Family that I belong to. It holds my family name and a couple of other fields. There is then a one-to-many relationship from that to the FamilyMember table. In this table I have a record for each member of my family. The FamilyMember table is also being used as the authentication table for my site. I have not replaced the default security model but only abstracted it and added additional fields. My children are students so they are in the Student table. Of course, they are in the FamilyMember table with a foreign key in the Students table. I am logged into the site as myself. Since my family_member_role is set to parent I should be able to enroll all of my children into their courses. The Schedule table contains a bunch of relationships that "glue" together a course in a course catalog, a semester, a set of teachers, a set of assistants, a set of students, etc. I don't think that this this matters in my question but I wanted to mention it just in case. *** There can be unlimited periods. For this semester, we might have 3 periods but next semester we might have 4 or 5. So, I have a table that stores the periods for each semester. On to my design question. >From the user perspective, I'm thinking of the following workflow. However, I don't know if there is a better way to architect it. A parent logs into the site. She clicks on the "Schedule" link for a specific Semester. She sees a list of classes that she can enroll her children in. It is grouped by periods (first hour, second hour, etc) and it looks something like below. Note, the co-op only meets twice a month and does not replace any of the children's actual curriculum. These classes can be very educational but are really designed more for social interaction. First Period Fun with math (1st - 3rd grade) Spelling games (1st - 3rd grade) C++ programming (4th - 5th grade) Sing and dance (4th - 5th grade) Second Period Science experiments (1st - 3rd grade) Computer games (1st - 3rd grade) Woodworking (4th - 5th grade) Public speaking (4th - 5th grade) Now, as a parent, I need to enroll my two children into classes. I have a 3rd grader and a 4th grader. I am NOT forced to enroll my children in classes that match their grades. I can enroll my 3rd grade child in the C++ programming class if I think that he can succeed in that class. So, how do I set up this enrollment? I have a couple of options that are floating around in my mind. The first option is to use the bootstrap accordian class (See OPTION 1 below). When a parent clicks on the "Fun with math" the list of their children are displayed as radio buttons. The parent can select either/or child. Both children /could/ be enrolled in the same first period if desired. Let's say that Mark is selected in the Math class. When the parent clicks on the "Spelling games" class, the same children list is displayed. If the parent selects Mark for this Spelling class, then the math class selection is cleared for Mark. So, Mark can only be enrolled in one class during First Period. As the parent moves on to Second Period, she can enroll her children just like she did during first period
modelformset_factory not validating multiple forms
Hopefully this is an easy one. I have read through the documentation, searched online and just can't find a way around this error. I have two formsets that I've displayed in one view. The second formset is not validating upon POST so it won't save to the database. None of the fields are required so there is no reason for it not to save. If I load the page and just click submit without changing anything I receive 20 "This field is required". They load at the top of the page and don't tell me what fields seem to be missing. Extra credit if you can correct my {{ form.error }} tag so that the error shows up next to the form field instead of the top of the page. You can see in my code that I've tried multiple things and none work. Here are my views: class FamilyBaseFormSet(BaseModelFormSet): def add_fields(self, form, index): super(FamilyBaseFormSet, self).add_fields(form, index) form.fields['state'].widget.attrs['class'] = 'input-mini' form.fields['zip_code'].widget.attrs['class'] = 'input-small' class FamilyMemberBaseFormSet(BaseModelFormSet): def add_fields(self, form, index): super(FamilyMemberBaseFormSet, self).add_fields(form, index) form.fields['first_name'].widget.attrs['class'] = 'input-small' form.fields['middle_name'].widget.attrs['class'] = 'input-mini' form.fields['last_name'].widget.attrs['class'] = 'input-small' form.fields['state'].widget.attrs['class'] = 'input-mini' form.fields['zip_code'].widget.attrs['class'] = 'input-small' def manage_family_member(request): FamilyInlineFormSet = modelformset_factory(Family, extra=0, formset=FamilyBaseFormSet) FamilyMemberInlineFormSet = modelformset_factory(FamilyMember, extra=0, formset=FamilyMemberBaseFormSet) if request.method == "POST": family_formset = FamilyInlineFormSet(request.POST, request.FILES, queryset=Family.objects.filter(id = '1'), prefix='f') family_member_formset = FamilyMemberInlineFormSet(request.POST, request.FILES, queryset=FamilyMember.objects.filter(family = '1'), prefix='fm') if family_formset.is_valid() and family_member_formset.is_valid(): family_formset.save() family_member_formset.save() else: family_formset = FamilyInlineFormSet(queryset=Family.objects.filter(id = '1'), prefix='f') family_member_formset = FamilyMemberInlineFormSet(queryset=FamilyMember.objects.filter(family = '1'), prefix='fm') context = RequestContext(request,{ 'family_formset': family_formset, 'family_member_formset': family_member_formset, }) return render_to_response("school/family/manage_family_members.html", context) Here is the template: {% extends 'school/base.html' %} {% block title %}{{object_name}} Form{% endblock %} {% block content %} This is very useful when enrolling your children in their courses. {% for dict in family_member_formset.errors %} {{ dict.errors }} {% for error in dict.values %} {{ error }} {% endfor %} {% endfor %} {{ family_formset.management_form }} {% for form in family_formset.forms %} {{ form.id }} Name {{ form.error }} {{ form.name }} Address 1 {{ form.error }} {{ form.address1 }} Address 2 {{ form.error }} {{ form.address2 }} City {{ form.error }} {{ form.city }} State {{ form.error }} {{ form.state }} Zip {{ form.error }} {{ form.zip_code }} Email {{ form.error }} {{ form.email_address }} phone_number {{ form.error }} {{ form.phone_number }} {% endfor %} {{ family_member_formset.management_form }} {% for form in family_member_formset.forms %} {{ form.id }} {{ form.first_name.error }} {{ form.error }} First {{ form.first_name }} {{ form.middle_name.error }} Middle {{ form.middle_name }} {{ form.last_name.error }} Last {{ form.last_name }} {{ form.address1_error }} Address 1 {{ form.address1 }} {{ form.address.error }} Address 2 {{ form.address2 }} {{ form.city.error }} City {{ form.city }} {{ form.state.error }} State {{ form.state }} {{ form.zip_code.error }} Zip {{ form.zip_code }} {{ form.email_address.error }} Email {{ form.email_address }} {% endfor %} {% csrf_token %} {% endblock %} -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. For more options, visit https://groups.google.com/groups/opt_out.
SOLVED: modelformset_factory not validating multiple forms
I found the problem! The fields were being processed as expected but since I am using the FamilyMember table as the authentication table I needed to include the username and other fields (as hidden). On Thursday, August 1, 2013 9:13:18 AM UTC-4, Chris Ryan wrote: > > Hopefully this is an easy one. I have read through the documentation, > searched online and just can't find a way around this error. > I have two formsets that I've displayed in one view. The second formset is > not validating upon POST so it won't save to the database. None of the > fields are required so there is no reason for it not to save. > > If I load the page and just click submit without changing anything I > receive 20 "This field is required". They load at the top of the page and > don't tell me what fields seem to be missing. Extra credit if you can > correct my {{ form.error }} tag so that the error shows up next to the form > field instead of the top of the page. You can see in my code that I've > tried multiple things and none work. > > > Here are my views: > > class FamilyBaseFormSet(BaseModelFormSet): > def add_fields(self, form, index): > super(FamilyBaseFormSet, self).add_fields(form, index) > form.fields['state'].widget.attrs['class'] = 'input-mini' > form.fields['zip_code'].widget.attrs['class'] = 'input-small' > > class FamilyMemberBaseFormSet(BaseModelFormSet): > def add_fields(self, form, index): > super(FamilyMemberBaseFormSet, self).add_fields(form, index) > form.fields['first_name'].widget.attrs['class'] = 'input-small' > form.fields['middle_name'].widget.attrs['class'] = 'input-mini' > form.fields['last_name'].widget.attrs['class'] = 'input-small' > > form.fields['state'].widget.attrs['class'] = 'input-mini' > form.fields['zip_code'].widget.attrs['class'] = 'input-small' > > def manage_family_member(request): > FamilyInlineFormSet = modelformset_factory(Family, extra=0, > formset=FamilyBaseFormSet) > FamilyMemberInlineFormSet = modelformset_factory(FamilyMember, > extra=0, formset=FamilyMemberBaseFormSet) > if request.method == "POST": > family_formset = FamilyInlineFormSet(request.POST, request.FILES, > queryset=Family.objects.filter(id = '1'), prefix='f') > family_member_formset = FamilyMemberInlineFormSet(request.POST, > request.FILES, > queryset=FamilyMember.objects.filter(family = '1'), > prefix='fm') > if family_formset.is_valid() and family_member_formset.is_valid(): > family_formset.save() > family_member_formset.save() > else: > family_formset = > FamilyInlineFormSet(queryset=Family.objects.filter(id = '1'), prefix='f') > family_member_formset = > FamilyMemberInlineFormSet(queryset=FamilyMember.objects.filter(family = > '1'), prefix='fm') > > context = RequestContext(request,{ > 'family_formset': family_formset, > 'family_member_formset': family_member_formset, > }) > return render_to_response("school/family/manage_family_members.html", > context) > > > > Here is the template: > > > > {% extends 'school/base.html' %} > {% block title %}{{object_name}} Form{% endblock %} > > {% block content %} > This is very useful when enrolling your children in their courses. > {% for dict in family_member_formset.errors %} > {{ dict.errors }} > {% for error in dict.values %} > {{ error }} > {% endfor %} > {% endfor %} > > {{ family_formset.management_form }} > {% for form in family_formset.forms %} > > {{ form.id }} > > Name > {{ form.error }} > {{ form.name }} > > > Address 1 > {{ form.error }} > {{ form.address1 }} > > > Address 2 > {{ form.error }} > {{ form.address2 }} > > > City > {{ form.error }} > {{ form.city }} > > > State > {{ form.error }} > {{ form.state }} > > > Zip > {{ form.error }} > {{ form.zip_code }} > > > Email > {{ form.error }} > {{ form.email_address }} > > > phone_number > {{ form.error }} > {{ form.phone_number }} > > {% endfor %} > > {{ family_member_fo
Parents can't enroll children in courses
I submitted this question in much, much more detail a couple of weeks ago but got no response. I'm thinking that maybe I gave you too much information. So, I thought I'd try just one more time. I have a table of family members. Some of them are students. These students are enrolled in one or more courses. I can't seem to create the necessary view to allow a parent to enroll his child or children into one or more courses. Ideally, I'd like to present him with a list of courses for each period and allow him to select only one course for each child for each period. The tables look something like this. The Schedule table is a table that contains Foreign Keys to other tables (about 10 of them). It contains NO other fields besides these foreign keys. class FamilyMember(AbstractUser): family = models.ForeignKey(Family, blank=True, null=True) family_member_role = models.ForeignKey(FamilyMemberRole, blank=True, null=True)#For our example, let's assume this is either a parent or a child ... class Student(models.Model): ... family_member = models.OneToOneField(FamilyMember) class Schedule(models.Model): ... semester = models.ForeignKey(Semester, verbose_name='Semester') student = models.ManyToManyField(Student, verbose_name='Students', blank=True, null=True) ... -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. For more options, visit https://groups.google.com/groups/opt_out.