Home:ALL Converter>Unable to add data to databse from models forms django

Unable to add data to databse from models forms django

Ask Time:2020-09-07T00:39:09         Author:Talha Anwar

Json Formatter

I am trying to send data from django forms to backend sqlite3. But I am unable to do so. I am not also getting any error or warning that help me to sort it out.

Here is models.py file

from django.db import models
    GENDER_CHOICES = [
    ('Male', 'M'),
    ('Female', 'F')]
class upload(models.Model):
    name = models.CharField(max_length=100)
    gender = models.CharField(max_length=10, choices=GENDER_CHOICES)
    phone = models.CharField(max_length=50,null=True)
    email=  models.EmailField(max_length=50,null=True)
    file=models.FileField(upload_to='uploads/')

    def __str__(self):
        return self.name

here is forms.py file

from django.forms import ModelForm
from .models import upload
class uploadForm(ModelForm):
    class Meta:
        model = upload
        fields = ['name', 'gender', 'phone', 'email','file']

Here is view.py file

from django.shortcuts import render
from .forms import uploadForm
from django.shortcuts import render
def home(request):
    if request.method == 'POST':
        form = uploadForm()
        if form.is_valid():
            form=form.save()
            return HttpResponseRedirect('/')
    else:
        form = uploadForm()

    return render(request,'home.html',{'print':form})

I am unable to understand where is the issue This is how template file look like

<form  method="post">
    {% csrf_token %}
    {{ print.as_p }}
    <input type="submit" value="Submit">
</form>

EDIT This issue is with FileField, I removed it, and it start saving in django database. What I want is to save file in media folder and other data in database

I also added enctype="multipart/form-data" in form

Author:Talha Anwar,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/63766480/unable-to-add-data-to-databse-from-models-forms-django
IdrisSan :

I don't think your actually sending anything to the database.\nWhere is says form = uploadForm() you need state you want the posted data to be sent. so this needs to be form = uploadForm(request.POST) it should then work I believe. Also when saving the form, remove the form=form.save() and leave it as form.save()\nTry it out and let us know?",
2020-09-06T17:13:20
yy