1

My code is pretty simple and straight forward. These are my forms

class LearningObjectiveForm( ModelForm ):
  class Meta:
    model = LearningObjective
    fields = ( 'learning_objective', 'topic', )

this is a snippet from my template

<form method="POST" action=".">
{% csrf_token %}
<table>
{{ form }}
</table>
<input type="submit" value="Speichern"/>
</form>

this form makes now every topic access able for every user. Since this field normally has a user restriction, I don't want that every topic is shown but just the topic for a certain user. The structure in my models for this specific case look like this

class Trainee( models.Model ):
  user = models.OneToOneField( User )
  first_name = models.TextField()
  last_name = models.TextField()
  education_beginning = models.DateField()
  comment = models.TextField( null = True, blank = True )

class Topic( models.Model ):
  trainee = models.ForeignKey( Trainee )
  topic = models.TextField()

class LearningObjective( models.Model ):
  trainee = models.ForeignKey( Trainee )
  topic = models.ManyToManyField( Topic, blank = True, null = True)
  learning_objective = models.TextField()

And my views

class LearningObjectiveView( LoginRequiredMixin, FormView ):
  form_class = LearningObjectiveForm( user = request.user )
  success_url = reverse_lazy( 'learning_objective' )
  template_name = 'learningobjective.html'

  def get_context_data( self, **kwargs ):
    trainee = Trainee.objects.get( user = self.request.user )
    context = super( LearningObjectiveView, self ).get_context_data( **kwargs )
    context['learningobjective'] = LearningObjective.objects.filter( trainee = trainee.id )
    context['topic'] = Topic.objects.filter( trainee = trainee.id )
    return context

  def form_valid( self, form ):
    self.object = form.save( commit = False )
    if self.request.user.is_authenticated():
      self.object.trainee = Trainee.objects.get( user = self.request.user )
    self.object.save()
    return super( LearningObjectiveView, self ).form_valid( form )

Topics should be trainee specific. Do I have to write my own form in the template or is there such a way so that I still can auto generate it?

2 Answers 2

1

You can modify the queryset attribute of the ModelChoiceField in the form init function and that will limit the choices as well as validate correctly.

The form will look something like the following code

class LearningObjectiveForm(ModelForm):
  class Meta:
    model = LearningObjective
    fields = ('learning_objective', 'topic',)

  def __init__(self, user, *args, **kwargs):
    super(LearningObjectiveForm,self ).__init__(*args,**kwargs)
    self.fields['topic'].queryset = Topic.objects.filter(trainee=user)

And then in the form make sure to call the form with the user LearningObjectiveForm(user=request.user)

5
  • Note that trainee is not a foreign key to User either.
    – Selcuk
    Mar 2, 2015 at 13:58
  • How are you linking the trainee to the User then? How do you know which trainee the request user is?
    – awwester
    Mar 2, 2015 at 14:20
  • 1
    Ok yeah that approach is going to get you in a LOT of trouble. Take a look at extending the user model. docs.djangoproject.com/en/1.7/topics/auth/customizing/… You can't tell which trainee is using the app with this approach.
    – awwester
    Mar 2, 2015 at 14:25
  • you need to call the form with the request argument, or actually it would be better to pass in the request.user object at this point. Here's an example stackoverflow.com/questions/1202839/…
    – awwester
    Mar 2, 2015 at 15:00
  • ok so you're using CBV, it's different with that (you didn't post anything showing that)... search how to get request in CBV, you're going to have to override the get_form_class method
    – awwester
    Mar 2, 2015 at 15:10
0

In addition to awwester's answer I added this to my view

class LearningObjectiveView( LoginRequiredMixin, FormView ):
    form_class = LearningObjectiveForm
    template_name = 'learningobjective.html'
    success_url = reverse_lazy( 'learning_objective' )

    def get_context_data( self, **kwargs ):
        trainee = Trainee.objects.get( user = self.request.user )
        context = super( LearningObjectiveView, self ).get_context_data( **kwargs )
        context['learningobjective'] = LearningObjective.objects.filter( trainee = trainee.id )
        context['topic'] = Topic.objects.filter( trainee = trainee.id )
        return context

    def get_form_kwargs( self ):
        kwargs = super( LearningObjectiveView , self ).get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

    def form_valid( self, form ):
        self.object = form.save( commit = False )
        if self.request.user.is_authenticated():
            self.object.trainee = Trainee.objects.get( user = self.request.user )
        self.object.save()
        return super( LearningObjectiveView, self ).form_valid( form )

The get_form_kwargs passes the kwarg user with the current user to the form. Then my Form finally looked like this:

class LearningObjectiveForm( ModelForm ):
    def __init__( self, user, *args, **kwargs ):
        trainee = Trainee.objects.get( user = user )
        super( LearningObjectiveForm, self ).__init__( *args, **kwargs )
        self.fields['topic'].queryset = Topic.objects.filter( trainee = trainee.id )

    class Meta:
        model = LearningObjective
        fields = ( 'learning_objective', 'topic', )

It works fine now, but if something is redundant or unnecessary please tell me :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.