Home > Enterprise >  how to insert data to database without forms.py in django
how to insert data to database without forms.py in django

Time:07-22

This method works fine for me can some one say how to add file or images like this

def insert_students(request);
    name = request.POST['name']
    class = request.POST['class']
    student = studentsmodels(name=name, class=class)
    student.save()
    return redirect('/')
return render(request, "insertpage.html")

CodePudding user response:

Using Django forms would make your life so much easier, frankly. However, you can still create objects without forms and add files to them. Instead of request.POST the files are stored in request.FILES the documentation goes into detail about how files are uploaded:

https://docs.djangoproject.com/en/4.0/topics/http/file-uploads/

CodePudding user response:

def submit_form(request):
    if request.method == POST:
       name = request.POST["name"]
       class = request.POST["class"]
       if Mymodel.objects.filter(name=name, class=class).exist():
          messages.infor("class and name already exist")
       else:
           MyModel.objects.create(name=name, class=class)
    return render(request, "submit_form.html)

submit_form.html

<form action="{% url 'submit_form' %}" method="post">
  {%csrf_token%}
<input name="name" placeholder="Enter Name" type="text">
<input name="class" type="text" placeholder="Enter Class">
<button 
            type="submit">submit
    </button>
</form>
  • Related