Home > Blockchain >  Django Form is not saving file to Database
Django Form is not saving file to Database

Time:12-06

views.py

from .forms import palForm
def add_form(request):
    if request.method!="POST":
        return HttpResponse("Method Not Allowed")
    else:
        form = palForm(request.POST, request.FILES)
        context = {"form": form}
        if form.is_valid():
            form.save()
            messages.success(request,"Successfully Added")
            return render(request,"home/pal-form.html",context)
        else:
            messages.error(request,"Failed to Add")
            return render(request,"home/pal-form.html",context)

forms.py

from django import forms
from .models import palabout

class palForm(forms.ModelForm):
    class Meta:
        model=palabout
        fields =['fname','lname','dob','gender','profileImage']

models.py

from pol.models import CustomUser
from django.db import models

class palabout(models.Model):
    user = models.ForeignKey(CustomUser, blank=True, null=True, on_delete=models.SET_NULL)
    profileImage = models.FileField()
    fname = models.CharField(max_length=30)
    lname = models.CharField(max_length=30)
    gender = models.CharField(
        max_length=1, choices=(('m', ('Male')), ('f', ('Female'))),
        blank=True, null=True)
    dob = models.DateField(max_length=8)

.html


<form role="form" action="{% url 'pal:add_form' %}" method="post" ,enctype="multipart/form-data">
            {% csrf_token %}
    
            <div id="profile-container">
                <image id="profileImage" src= "{{pic.url}}" style="width:100px" /></div>
                <input id="imageUpload" type="file" name="profile_photo" placeholder="Photo" required="" capture>
                <div >
                    
                        <ul >
                            <li>
                                <ul >
                                    <li>    
                                        <label for="fname"><strong>First Name </strong></label>
                                        <input type="text" id="fname" tabindex="1"  /> 
                                    </li>
                                </ul>
                            </li>
                            <li>
                                <ul >
                                    <li>
                                        <label for="lname"> <strong> Last Name </strong></label>
                                        <input type="text" id="lname" tabindex="1" />
                                    </li>
                                </ul>
                            </li>
                            <li>
                                <ul >
                                    <li>
                                        <tr>
                                            <td for="gender"><strong>Sex:</strong></td>
                                            <td><input type="radio" name="gender" value="male" required>Male
                                            <input type="radio" name="gender" value="female">Female</td>
                                            <td>&nbsp;</td>
                                        </tr>
                                    </li>
                                </ul>
                            </li>
                            <li>
                                <ul >
                                    <li>
                                        <label for="dob"> <strong> Date of birth </strong></label>
                                        <input type="date" id="dob" value="YY-DD-MM" max="2040-01-01" >
                                    </li>
                                </ul>
                            </li>
                            
                            <ul >
                                <li>
                                    {% if messages %}
                                    {% for message in messages %}
                                    {% if message.tags == 'error' %}
                                    <div  style="margin-top:10px">{{ message }}</div>
                                    {% endif %}
                                    {% if message.tags == 'success' %}
                                    <div  style="margin-top:10px">{{ message }}</div>
                                    {% endif %}
                                    {% endfor %}
                                    {% endif %}
                                </li>
                            </ul>
                        </li>
                    </ul>
                    <div >
                        <ul>
                            <li>
                                <button style='margin-top:10px;' type='submit' >Save</button>
                            </li>
                        </ul>
                    </div>
                </form>


I'm trying a lot saving my database, but it's failed because many times i have got failed to Add but not successfully in my pages on database. Can you tell me what's problem in my page?

CodePudding user response:

According to your views, you are rendering template after else statement.

Instead of this:

   else:
        messages.error(request,"Failed to Add")
        return render(request,"home/pal-form.html",context) #here you made mistake so that's why it is not saving.

Do this:

   else:
        messages.error(request,"Failed to Add")
   return render(request,"home/pal-form.html",context)

And in your tempalate, you have not passed form fields in inputs. let's pass it:

<form role="form" action="{% url 'pal:add_form' %}" method="post" ,enctype="multipart/form-data">
            {% csrf_token %}
    
            <div id="profile-container">
                <image id="profileImage" src= "{{pic.url}}" style="width:100px" /></div>
                <input id="imageUpload" value="{{form.profileImage}}" type="file" name="profile_photo" placeholder="Photo" required="" capture> #here added form field
                <div >
                    
                        <ul >
                            <li>
                                <ul >
                                    <li>    
                                        <label for="fname"><strong>First Name </strong></label>
                                        <input type="text" id="fname" tabindex="1" value="{{form.fname}}" /> #here added form field
                                    </li>
                                </ul>
                            </li>
                            <li>
                                <ul >
                                    <li>
                                        <label for="lname"> <strong> Last Name </strong></label>
                                        <input type="text" id="lname" tabindex="1" value="{{form.lname}}" /> #here added form field
                                    </li>
                                </ul>
                            </li>
                            <li>
                                <ul >
                                    <li>
                                        <tr>
                                            <td for="gender"><strong>Sex:</strong></td>
                                            <td><input type="radio" name="gender" value="{{form.gender}}" required>Male
                                            <input type="radio" name="gender" value="{{form.gender}}">Female</td> #here added form field
                                            <td>&nbsp;</td>
                                        </tr>
                                    </li>
                                </ul>
                            </li>
                            <li>
                                <ul >
                                    <li>
                                        <label for="dob"> <strong> Date of birth </strong></label>
                                        <input type="date" id="dob" value="{{form.gender}}" max="2040-01-01" > #here added form field
                                    </li>
                                </ul>
                            </li>
                            
                            <ul >
                                <li>
                                    {% if messages %}
                                    {% for message in messages %}
                                    {% if message.tags == 'error' %}
                                    <div  style="margin-top:10px">{{ message }}</div>
                                    {% endif %}
                                    {% if message.tags == 'success' %}
                                    <div  style="margin-top:10px">{{ message }}</div>
                                    {% endif %}
                                    {% endfor %}
                                    {% endif %}
                                </li>
                            </ul>
                        </li>
                    </ul>
                    <div >
                        <ul>
                            <li>
                                <button style='margin-top:10px;' type='submit' >Save</button>
                            </li>
                        </ul>
                    </div>
                </form>

CodePudding user response:

Try using django for rendering the form, like or use the name='same_as_field_name' attribute for fields

<input type="text" name='fname' id="fname" tabindex="1"  /> 
<input type="text" name='lname' id="lname" tabindex="1" />
.....
.....

or

{{form.fname}}
{{form.lname}}
....
....

for getting correct error, then change messages.error(request,"Failed to Add") to

messages.error(request,form.errors)

CodePudding user response:

It looks like the issue is with the HTML form not having the correct field names for the Django form. In the HTML form, the input elements for fname, lname, gender, and dob do not have name attributes, so when the form is submitted, Django does not know which form fields to populate with the submitted data.

To fix this, you can add name attributes to the input elements in the HTML form, like this:

<input type="text" id="fname" name="fname" tabindex="1" />

You should do this for all the input elements in the form that correspond to fields in the Django form.

In addition, the input element for the profileImage field does not have a name attribute, and it is also missing the type="file" attribute, which is necessary for file uploads. The correct HTML for this field would be:

<input type="file" name="profileImage" id="imageUpload" placeholder="Photo" required="" capture>

Once you have made these changes, the form should be able to save the data to the database correctly.

  • Related