1
votes

I am trying to save a file and some other details in django using forms. And I only want it to save a CharField and a FileField but not the country field. For country field I want it to take its value through a post request. But the form isn't saving. The errors says "data didn't validate". Also this method works fine if I don't use a FileField.

models.py

class Simple(models.Model):
    name = models.CharField(max_length=100)
    city = models.FileField(upload_to='marksheet')
    country = models.CharField(max_length=100)

forms.py

class SimpForm(forms.ModelForm):
    class Meta:
        model = Simple
        fields = ['name','city']

A snippet from upload.html

<form action="upload" method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        <label>Test input</label>
        <input type="text" name="country">
        {{form.name}}
        {{form.city}}
        <button type="submit">Submit</button>
</form>

views.py

def upload(request):
    if request.method == 'POST':
        a = request.POST.get('country')
        form = SimpForm(request.POST,request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.country = a
            post.save()
            return HttpResponse('saved')
        else:
            return HttpResponse('ERROR SAVING')
    else:
        form = SimpForm()
        return render(request,'upload.html',{'form':form})
1
It'd be helpful if you can paste the full error stacktrace. - Nitin Prakash

1 Answers

1
votes

You are not passing request.FILES in your form. You should pass it like this:

form = SimpForm(request.POST, request.FILES)

More information on file uploads can be found in documentation.