1

I have a following model:

class Question(models.Model):
    section = models.ForeignKey(Section)
    description = models.TextField()
    answer = models.TextField(blank=True, null=True)
    author = models.ForeignKey(settings.AUTH_USER_MODEL)

Corresponding form is

class QuestionForm(forms.ModelForm):
    class Meta:
        model = Question
        fields = ('description', 'section', 'author')

My question is how can I pass to the form value of author? Author is currently logged user (request.user is not accessible).

Thank you.

3 Answers 3

3

You could pass the user from the view to the form and ovewrite the __init__ method on form to change the initial value of your field:

view.py (using CBV) something like:

class SomethingView(FormView):
    def get_form_kwargs(self, *args, **kwargs):
        return dict(
            super(SomethingView, self).get_form_kwargs(*args, **kwargs),
            **{'user': self.request.user}
        )

forms.py something like:

class SomethingForm(forms.modelForm):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        self.fields['user'].initial = self.user.id
        super(SomethingForm, self).__init__(*args, **kwargs)
Sign up to request clarification or add additional context in comments.

2 Comments

this is if you want to change the initial value of a field... but since the user reference is stored in self.user, you can now use it everywhere on the form
Thanks. This worked. Just needed to place super(SomethingForm, self).__init__(*args, **kwargs) before self.fields['user'].initial = self.user.id
0

In your view you can pass an initial value to the form when you instantiate it. You can read more about it here: https://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values

Comments

0

If you don't want to allow user to set any other user as author of this question, you should set this field in a view and remove 'author' from form fields.

For example, if you use generic class based views:

class CreateQuestionView(generic.CreateView):
    model = Question
    form_class = QuestionForm

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super(CreateQuestionView, self).form_valid(form)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.