Home > Back-end >  How do you pass request data to Forms in Django?
How do you pass request data to Forms in Django?

Time:10-26

here I am using model forms and trying to make my placeholder dynamic. my approach is to take request data, pass it into widgets with f string.

what I am trying to achieve is

{'placeholder': f"commenting as {request.user.username}"}

HERE IS MY CODE.

class CommentForm(ModelForm):
class Meta:
    model = Comment
    fields = ("body",)
    widgets = {
        "body": forms.TextInput(
            attrs={
                "placeholder": "Enter your comment",
                "class": "comment-form-text",
            }
        ),
    }
    labels = {
        "body": "",
    }

CodePudding user response:

This is how I usually pass the request object in a form.

Note: all you need is the CommentForm.__init__ and calling it with CommentForm(request.POST, request=request)
I just added the custom save, but commented it out, to show you can also access it there and do some cool things! :-)

forms.py
class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = ("body",)
        widgets = {
            "body": forms.TextInput(
                attrs={
                    "class": "comment-form-text",
                }
            ),
        }
        labels = {
            "body": "",
        }
    def __init__(self,  *args, **kwargs):

#        # Keeping track of if it's an edit form or not ( Not Required, but handy )
#        self.is_edit =  True if 'instance' in kwargs else False

        # Store Request Object
        self.request = kwargs.pop('request') if 'request' in kwargs else None

        super(CommentForm, self).__init__(*args, **kwargs)

        # You can add *Any* custom attribute here to any field
        self.fields['body'].widget.attrs={'placeholder': 'commenting as {0}'.format(self.request.user.username)}


#    # Just showing that you can also use it in a Custom Save Method :-)
#    def save(self, commit=True):
#        obj = super(CommentForm, self).save(commit=False)
#
#        # Note: Keeping track of **if** it's an edit so we don't re-add to the field!
#        if not self.is_edit:
#            # Use Request to fill a field (New)
#            obj.creator = request.user
#        else:
#            # Use request to fill a field (edit)
#            obj.last_editor = request.user
views.py
def commentformview(request):
    form = CommentForm(data=request.POST or None, request=request)

    if request.method == 'POST':
        if form.is_valid():
            form.save()
            # redirect

    data = {
        'form': form,
        }
    return render(request, 'commentform.html', data)
  • Related