Saturday, April 5, 2014

New to Django - How to add inline object to the parent object via shell command or scripts

I am trying to learn how to use Django.

I created 2 very simple models:

models.py

class Course(models.Model):
    name = models.CharField(max_length=100)
    instructor = models.CharField(max_length=100)

    student = models.ForeignKey('Student', null=True, blank=True)

    def __str__(self):
        return (self.name)

class Student(models.Model):
    name = models.CharField(max_length=100)
    courses = RelatedObjectsDescriptor()

    def __str__(self):
        return (self.name)

forms.py

class CourseInline(admin.TabularInline):
    model = Course
    form = CourseForm
    extra = 3

class StudentAdmin(admin.ModelAdmin):
    form = StudentForm
    search_fields = ('name', )
    fields = ('name', )
    ordering = ('name',)

    inlines = [CourseInline]
 
admin.site.register(Student, StudentAdmin)


with this setup, I can add student then add courses to the student.

What I am trying to do is to use script to enter the known records:

student = Student(name ='student1')                                                                    - This work
course = Course(name='Math101", instructor="Smith", student=student)                - This work, but when I view the student record via admin page, the course does not show up as an inline object

My problem id how to add the courses to this student as I add them through the admin page.

Thank you very much for any help.


--
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+unsubscribe@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.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/c19e368b-907d-4b07-bf45-de95c8ae333b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment