[Fixed]-Form data not getting saved in django

0👍

Age was missing in model form Fields

1👍

if form.is_valid():
    # save a UserDetails obj (data are automatically get from the form) to db.
    form.save()

    # Get data from form
    uname = form.cleaned_data['uname']
    fname = form.cleaned_data['first_name']
    pword = form.cleaned_data['pword']
    email = form.cleaned_data['email']
    contact = form.cleaned_data['contact']
    lname = form.cleaned_data['last_name']

    # Check if user already exists. If it doesn't, create it
    if not User.objects.filter(username=uname, email=email).exists():
        user=User.objects.create_user(uname, password=pword, email=email)

    #stuff after registration
    message = "registration done! login again"
    return render(request,'register.html',locals())

See more on the ModelForm‘s save() method.

However, I noticed that the age model field is required. So, the save() will complain. You should better make it as: age = models.IntegerField(blank=True, null=True) or define a default value like this age = models.IntegerField(default=20). Although, defining a default age is awkward, better follow the blank=True null=True to allow empty ages.

👤nik_m

Leave a comment