Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my Django form not "valid"? Can't get the POST request to update database

I am trying to create a user profiles for users in my Django app. I have the form displaying where I want it to and when I try to submit, nothing happens. I put a print statement after the form.is_valid in my view.py and found that it wasn't 'valid' but I have no idea why. I have tried several different ways to 'clean' / 'validate' data but I can't get past the form being 'invalid.'

Any help would be greatly appreciated!

urls:

path('userinfo/', views.user_info, name='userinfo')

form template:

{% extends "base.html" %}

{% load bootstrap4 %}

{% block content %}
<div class="container">
  <h1>Enter User Info</h1>
<form method="POST" class="form">
 {% csrf_token %}
 {% bootstrap_form form %}

 <input type="submit" class="btn btn-primary" value="Create Profile">

 </form>
</div>
{% endblock %}

view:

def user_info(request):

form = ProfileForm()

if request.method == 'POST':
    form = ProfileForm(request.POST)
    if form.is_valid():
        form.save()
    else:
        form = ProfileForm()

return render(request, 'miraDashboard/form.html', context={'form': form})

model:

from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    name = models.CharField("Full Name", max_length=1024)
    job_role = models.CharField("Role", max_length=254, default="Seeking Job Opportunities")
    zip_code = models.CharField("Zip Code", max_length=5)
    user_image = models.ImageField("Upload Profile Picture", upload_to='images/')
def __str__(self):
    return f'{self.user.username} Profile'

form:

from django.forms import ModelForm
from .models import Profile

class ProfileForm(ModelForm):

class Meta:
    model = Profile
    fields = ['name','job_role','zip_code', 'user_image']
like image 639
Faisal Malik Avatar asked Jan 23 '26 05:01

Faisal Malik


1 Answers

if you want to see errors in form change else statmant:

def user_info(request):

form = ProfileForm()

if request.method == 'POST':
    form = ProfileForm(request.POST)
    if form.is_valid():
        form.save()
    else:
        print(form.errors.as_data()) # here you print errors to terminal


return render(request, 'miraDashboard/form.html', context={'form': form})

after form.is_valid() you don't need to set it again (form = ProfileForm() in else statment). this way your form will get errors( you cen see them in form.errors).

like image 151
Waldemar Podsiadło Avatar answered Jan 24 '26 18:01

Waldemar Podsiadło



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!