1

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. Commented May 14, 2020 at 6:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you so much for answering.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.