On Saturday, 5 April 2014 09:21:38 UTC+1, H. Pham wrote:
-- I am trying to learn how to use Django.
Then you should read the tutorial.
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)
This is wrong. This means each course can only have one student. The ForeignKey should be on Student, pointing to Course. Or, more likely, you should have a ManyToManyField, since Courses can have many students, and Students can have many classes.
def __str__(self):
return (self.name)
class Student(models.Model):
name = models.CharField(max_length=100)
courses = RelatedObjectsDescriptor()
Is this from the genericm2m project? If so, you should say so. But there's no need for it here: a simple ManyToManyField is what you need.
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)
This stuff should be in admin.py
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
You've confused yourself by trying to use that genericm2m project. Stick to the standard classes for now.
course = Course.objects.create(name="math101', instructor='Smith')
course.students.add(student)
This is all well covered in the tutorial, which you should read rather than relying on random blog posts.
--
DR.
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/f996b553-fe02-47c5-9fc4-7f047b9f91bd%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment