Paul R
Paul R

Reputation: 2797

Django default value for form

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.

Upvotes: 1

Views: 2515

Answers (3)

kubus
kubus

Reputation: 783

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)

Upvotes: 0

pleasedontbelong
pleasedontbelong

Reputation: 20102

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)

Upvotes: 3

Daniel Rosenthal
Daniel Rosenthal

Reputation: 1386

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

Upvotes: 0

Related Questions