Search code examples
djangoforeign-keystemplate-inheritance

Populating foreign key fields in Django


In my first app (course) I'm creating courses. Each course has number of chapters and each chapter has quiz. I'm trying to create quiz using second app (quiz). models.py (quiz) :

class Quiz(models.Model):
    coursechapter = models.ForeignKey(CourseChapter)
    name = models.CharField(max_length=255, verbose_name=u'Quiz name',)
    creator = models.ForeignKey(User)
    creation = models.DateField(auto_now_add=True)
    def __unicode__ (self):
        return self.name

class Question(models.Model):
    quiz = models.ForeignKey(Quiz)
    text = models.CharField(max_length=255, verbose_name=u'Question\'s text')


class QuestionAnswer(models.Model):
    question = models.ForeignKey(Question)
    text = models.CharField(max_length=255, verbose_name=u'Answer\'s text')
    is_valid = models.BooleanField(default=False)

class UserAnswer(models.Model):
    answer = models.ForeignKey(QuestionAnswer)

I have template for creating courses, inside that template i have link (Add chapters) which takes me to another template(view) for creating chapters. Inside i have link to create quiz for that specific chapter. That link leads to url: /quiz/new (using url.py from quiz app) which is represented by view.py (from quiz app) . Problem is i dont know how to get id of chapter for which I'm creating quiz. Example of chapter url (one before user click Create Quiz) /course/new/chapter/197/ , is it possible to somehow send chapter_id (197) through link or is there any other way? views.py(Quiz):

class CreateQuizView(CreateChapterView):
    model = Quiz
    template_name = 'quiz/create_quiz.html'
    fields = '__all__'

    def dispatch(self, request, *args, **kwargs):
        self.pk = kwargs.get('pk')
        return super(CreateQuizView, self).dispatch(request, *args, **kwargs)
    def get_success_url(self):
        return reverse('quiz-list',
                                    kwargs={'pk': Quiz.objects.latest('id').id})

    def get_context_data(self, **kwargs):       

        context = super(CreateQuizView, self).get_context_data(**kwargs)
        return context

views.py(Course):

class CreateChapterView(CreateView, GroupRequiredMixin):
    model = CourseChapter
    template_name = 'course/add_chapter.html'
    fields = '__all__'
    def dispatch(self, request, *args, **kwargs):
        self.pk = kwargs.get('pk')
        return super(CreateChapterView, self).dispatch(request, *args, **kwargs)
    def get_success_url(self):
        return reverse('courses-chapters',
                                    kwargs={'pk': Course.objects.latest('id').id})

    def get_context_data(self, **kwargs):       

        context = super(CreateChapterView, self).get_context_data(**kwargs)
        context['chapter'] = CourseChapterForm
        context['chapters'] = CourseChapter.objects.all()
        context['last'] = Course.objects.latest('id')
        context['courses'] = Course.objects.all()
        context['action'] = reverse('courses-chapters',
                                    kwargs={'pk': Course.objects.latest('id').id})
        context['kw'] = self.kwargs
        context['quiz'] = QuizForm()
        context['question'] = QuestionForm()
        context['answer'] = QuestionAnswerForm

        return context

    def form_valid(self, form):
        self.object = form.save()
        # chapters = CourseChapter.objects.filter(course_id=Course.id)
        return  HttpResponseRedirect(self.get_success_url())

urls.py (main)

url(r'^course/', include('course.urls')),
url(r'^quiz/', include('quiz.urls', namespace="quiz")),

urls (course)

url(r'^new/$', course.views.CreateCourseView.as_view(),
    name='courses-new',),
url(r'^new/(?P<pk>\d+)/$', course.views.CreateChapterView.as_view(),
    name='courses-chapters'),
url(r'^edit/(?P<pk>\d+)/$', course.views.UpdateCourseView.as_view(),
        name='courses-edit',),
url(r'^new/chapter/(?P<pk>\d+)/$', course.views.CreateChapterView.as_view(),
        name='chapter-content',),
url(r'^edit/chapters/(?P<pk>\d+)/$', course.views.UpdateChapterView.as_view(),
        name='chapters-edit',),

urls (quiz):

urlpatterns = [
    url(r'^$', quiz.views.ListQuizView.as_view(),
        name='quiz-list',),
url(r'^new/$', quiz.views.CreateQuizView.as_view(),
    name='quiz-new',),
    ]

Solution

  • You mentioned that you have a link for creating quiz in your page where you create chapters. I suggest you create link right there itself.

    For eg,

    lets say you have course 'Learn Python' which has chapter called Introduction and it has id 7, you can format your url as such /add-quiz/chapter/chapter_id. You will have chapter in the page if you pass it from the view.