1

I have my response form and view like this

class ResponseForm(ModelForm):
    class Meta:
        model = ResponseModel
        exclude = ('author', 'title','submit_count')
        # help_texts = {
        #     'ans1': user.q1.value,
        # }

@login_required
def ResponseFormView(request):
    if request.method == "POST":
        form = ResponseForm(request.POST)
        if form.is_valid():
            submission = form.save(commit=False)
            submission.author = request.user
            submission.save()
            return render(request, 'thanks.html', {})
    else:
        form = ResponseForm()
        return render(request, 'response_tem.html', {'form': form})

I want the help text for 'ans1' field to be the value of q1 field of request.user. How do I do it?

1 Answer 1

3

You can do it like this:

class ResponseForm(ModelForm):
    def __init__(self, *args, **kwargs):
         user = kwargs.pop('user', None)  # popping user from known arguments
         super(ResponseForm, self).__init__(*args, **kwargs) 
         if user:
              self.fields['ans1'].help_text = "Help Text for {}".format(user.username)

    class Meta:
        model = ResponseModel
        exclude = ('author', 'title','submit_count')

@login_required
def ResponseFormView(request):
    if request.method == "POST":
        form = ResponseForm(request.POST)
        if form.is_valid():
            submission = form.save(commit=False)
            submission.author = request.user
            submission.save()
            return render(request, 'thanks.html', {})
    else:
        form = ResponseForm(user=request.user)  # passing user as known argument
        return render(request, 'response_tem.html', {'form': form})

Here, in the view I am passing the request.user as known argument when I am initiating Form Class's Object (marked with comment). Then in the Form, I am catching the user sent from view and updating the field's help text.

Sign up to request clarification or add additional context in comments.

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.