Home > database >  ModelForm doesn´t validate
ModelForm doesn´t validate

Time:11-25

I just cant make my modelform to validate. I call it from view, and GET prints it right, but when POST occurs it doesn´t validate. Allways getting

ValueError Exception Value: The view gestionPartesMedicos.views.partes_medicos_add didn't return an HttpResponse object. It returned None instead.

form´s name attributes correspond to model´s and form´s.

---UPDATED---

This my model:

class MedicalList(models.Model):
    worker= models.ForeignKey(worker, on_delete=models.CASCADE)
    description=models.CharField(max_length=255)
    upload=models.FileField(upload_to=user_directory_path, null=False, blank=False)
    created_at=models.DateTimeField(auto_now_add=True)

this my form class:

class MedicalListForm(forms.ModelForm):
    
worker = forms.ModelChoiceField(
    queryset=Worker.objects.none(),
    empty_label=None,
    widget=forms.Select(attrs={'class': 'form-control'})
)
description=forms.CharField(
    widget=forms.Textarea(attrs={'class': 'form-control'})
)
upload=forms.FileField(
    widget=forms.ClearableFileInput(attrs={'class': 'form-control'})
)

class Meta:
    model = MedicalList
    fields = ( 
        'worker',
        'description',
        'upload',
    )

def __init__(self, *args, **kwargs):
    user_id = kwargs.pop('user_id', None)
    super().__init__(*args, **kwargs)
    self.fields['worker'].queryset = Worker.objects.filter(user_id=user_id)

And this my view in trouble:

def medical_list_add(request):
    if request.method == "POST":
        form = MedicalListForm(request.POST,request.FILES,user_id=request.user)
        
        if form.is_valid():
            form.save()
            return redirect('medical_list')
    else:
        form = MedicalListForm(user_id=request.user)
        return render(request, 'medical_list_add.html', {'form': form})

The form in template:

<form method="POST">
            {% csrf_token %}
                <div class="form-group">                
                    {{ form.as_p }}
                    <button type="submit" class="btn btn-primary">Guardar</button>
                    <a class="nav-item linking" href = "{% url 'medical_list' %}">Cancel</a>
                </div>
            </form>

this is the response I get:

Request information USER 12345

GET No GET data

POST Variable Value csrfmiddlewaretoken
'2zG3amQlZlPsrytMtF91ZiJQDZ679E2Zgrx3YxcOPzcNj6dNCl101Lj0UV96STLY' worker '14' description 'pm' upload 'medical.pdf'

Might it be around Model field created_at? just trying to guess, totally lost. thanks in advance

CodePudding user response:

The main problem is that your view does not return a HTTP response in case the form was invalid. You should unindent the render(…) call with:

def medical_list_add(request):
    if request.method == "POST":
        form = MedicalListForm(request.POST,request.FILES,user_id=request.user)
        
        if form.is_valid():
            form.save()
            return redirect('medical_list')
    else:
        form = MedicalListForm(user_id=request.user)
    # ↓↓ both for GET and a failed POST
    return render(request, 'medical_list_add.html', {'form': form})

Furthermore the form fields are specified at class level. By constructing a form field in the __init__ method, this will not use that

class MedicalListForm(forms.ModelForm):
    worker = forms.ModelChoiceField(
        queryset=Trabajador.objects.none(),
        empty_label=None,
        widget=forms.Select(attrs={'class': 'form-control'})
    )
    description=forms.CharField(
        widget=forms.Textarea(attrs={'class': 'form-control'})
    )
    upload=forms.FileField(
        widget=forms.ClearableFileInput(attrs={'class': 'form-control'})
    )
    
    class Meta:
        model = MedicalList
        fields = ( 
            'worker',
            'description',
            'upload',
        )

    def __init__(self, *args, **kwargs):
        user_id = kwargs.pop('user_id', None)
        super().__init__(*args, **kwargs)
        self.fields['worker'].queryset = worker.objects.filter(user_id=user_id)

If your form handles files, you should set the enctype=… parameter to multipart/form-data:

<form method="POST" enctype="multipart/form-data"></form>
  • Related