Aboulezz
Aboulezz

Reputation: 11

Get the current logged user in the django form

I am making a blog website , which each user cannot post more than 3 blogs

so I wrote that in the form.py file so it can validate the number of blogs before submitting

this is the form code

class BlogForm(forms.ModelForm):
blog=forms.CharField(label='',
            widget=forms.Textarea(
                    attrs={'placeholder': "Your blog",
                        "class": "form-control",
                        }
                ))

def __init__(self, *args, **kwargs):
    self.user = kwargs.pop('user')
    super(BlogForm, self).__init__(*args, **kwargs)

def clean(self):
    cleaned_data=super(BlogForm, self).clean()
    user=cleaned_data.get(self.request.user)
    if Blog.objects.filter(user=user).count()>=3:
        raise forms.ValidationError("You have exceeded limit.")

class Meta:
    model=Blog
    fields = ['user',
              'blog',
             'tags']

My Class Based View for the blog creation

class BlogCreateView(FormUserNeededMixin,CreateView):
form_class = BlogForm
template_name = 'blog/createview.html'
success_url = reverse_lazy('home')
form = BlogForm(user=request.user)

Expected Result : By the fourth blog submission of the same logged user , "You have exceeded limit." this error must appear

Actual :'BlogForm' object has no attribute 'request' this error appear

Upvotes: 0

Views: 256

Answers (2)

Exprator
Exprator

Reputation: 27503

class BlogForm(forms.ModelForm):
blog=forms.CharField(label='',
            widget=forms.Textarea(
                    attrs={'placeholder': "Your blog",
                        "class": "form-control",
                        }
                ))

add this method to your Form Class

def __init__(self,user, *args, **kwargs):
        // do something with user

in view function

form_class = BlogForm
def get_form_kwargs(self, *args, **kwargs):
    kwargs = super().get_form_kwargs(*args, **kwargs)
    kwargs['user'] = self.request.user
    return kwargs

Upvotes: 1

ruddra
ruddra

Reputation: 51948

You need to pass the request object to your form. if you are using method based views then do it like this:

def some_view(request):
    form = BlogForm(request.POST,request=request)

if you are using class based view, then override get_form_kwargs() method:

class SomeView(CreateView):

   def get_form_kwargs(self, *args, **kwargs):
     form_kwargs = super(SomeView).get_form_kwargs(*args, **kwargs)
     form_kwargs['request'] = self.request
     return form_kwargs

Then override the BlogForm to accept the request from view:

class BlogForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        request = kwargs.pop('request', None)
        if request:
           self.request = request
        super(BlogForm, self).__init__(*args, **kwargs)

Then you should be able to access request object in self.request

Upvotes: 0

Related Questions