Home > Mobile >  django form request post not loading data
django form request post not loading data

Time:11-13

I have am trying to load submitted data into a Form instance, request.POST has valid value but form does not.

class ArticleCreateForm(forms.Form):
    title = forms.CharField(max_length=255, widget=forms.TextInput(attrs={'autocomplete': 'off'}), label='')
    tagging = forms.CharField(max_length=255, required=False, widget=forms.TextInput(attrs={'autocomplete': 'off'}), label='')
    towhere = forms.CharField(max_length=20, required=False) # default to unchecked, save

    class Meta:
        fields = ['title', 'tagging', 'towhere']

    def clean_title(self):
        data = self.cleaned_data['title']
        if len(data) < 3:
            raise ValidationError('Title is too short')

    def clean_tagging(self):
        data = self.cleaned_data['tagging']
        if len(data) == 0 or data is None:
            raise ValidationError('Please add at least one tag')
@login_required
def articleChangeView(request, pk):
    try:
        article = Article.objects.get(pk=pk)
        if article.author != request.user:
            raise PermissionDenied()
        elif request.method == 'POST':
            form = forms.ArticleCreateForm(request.POST)
            print('--------')
            print(request.POST)
            print(form.cleaned_data)
<QueryDict: {'csrfmiddlewaretoken': ['gm0ODMFud35nhHlPdBr3IHVZXgtiDQV8zGPsscGWzcpylNVd0fnray7iodJvBWyb'], 'title': ['Title'], 'tagging': ['jquery']}>
{'title': None, 'tagging': None, 'towhere': ''}

I wonder why this happens, I will be so glad if you can give me a hand

CodePudding user response:

You first should call form.is_valid() [Django-doc]:

from django.shortcuts import get_object_or_404

@login_required
def articleChangeView(request, pk):
    article = get_object_or_404(Article, pk=pk, author=request.user)
    if request.method == 'POST':
        form = forms.ArticleCreateForm(request.POST)
        if form.is_valid():
            print('--------')
            print(request.POST)
            print(form.cleaned_data)

The clean methods of your clean_fieldnames should also return the cleaned value, so:

class ArticleCreateForm(forms.Form):
    # …

    def clean_title(self):
        data = self.cleaned_data['title']
        if len(data) < 3:
            raise ValidationError('Title is too short')
        return data

    def clean_tagging(self):
        data = self.cleaned_data['tagging']
        if not data:
            raise ValidationError('Please add at least one tag')
        return data
  • Related