0

Since django User model had only few fields in it, I made a custom model and used it's ModelForm to save data to User model and the custom model. The models.py is as shown below

from django.db import models
from django.contrib.auth.models import User
# Create your models here.
import datetime
class Post(models.Model):
    Author=models.ForeignKey(User)
    title=models.CharField(max_length=66)
    content=models.TextField()
    created_date=models.DateField(default=datetime.datetime.now())
    published_date=models.DateField()
    def publish(self):
        self.published_date=datetime.datetime.now()
        self.save()



class UserDetails(models.Model): #the custom model
    uname=models.CharField(max_length=55)
    first_name=models.CharField(max_length=55)
    last_name=models.CharField(max_length=55)
    age=models.IntegerField()
    contact=models.CharField(max_length=13)
    email=models.EmailField()
    pword=models.CharField(max_length=55)

modelform :

class RegisterForm(ModelForm):
    class Meta:
        model=UserDetails
        fields=['uname','pword','first_name','last_name','email','contact']

the views.py is like this

from django.shortcuts import render
from .models import UserDetails
# Create your views here.
from django.contrib.auth import authenticate,login,logout
from .forms import RegisterForm,LoginForm,PostForm
from django.contrib.auth.models import User
from django.db import IntegrityError
def register(request):
    if request.method=='POST':
        form=RegisterForm(request.POST)
        try:
            if form.is_valid():
                form.save()
                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']
                user=User.objects.create_user(uname,password=pword,email=email)
                user.last_name=lname
                user.save()
                #form.save()
                #stuff after registration
                message="registration done! login again"
                return render(request,'register.html',locals())
        except IntegrityError:
            message="username already exists!! try another"
    else:
        form=RegisterForm()
    return render(request,'register.html',locals())

The problem is that even if I make a fresh entry to the RegisterForm, the 'message' I get is, username already exists!! try another. The auth.User model is getting updated but UserDetails is not. What am I doing wrong? (spare me if this is a stupid question :) )

update: 1

from django.shortcuts import render
from .models import UserDetails
# Create your views here.
from django.contrib.auth import authenticate,login,logout
from .forms import RegisterForm,LoginForm,PostForm
from django.contrib.auth.models import User
from django.db import IntegrityError
def register(request):
    if request.method=='POST':
        form=RegisterForm(request.POST)
        try:
            if form.is_valid():
                form.save()
                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']
                if not User.objects.filter(username=uname,email=email).exists():
                    user=User.objects.create_user(uname,password=pword,email=email)
                    user.last_name=lname
                    user.save()
                message="registration done! login again"
                return render(request,'register.html',locals())
        except IntegrityError:
            message="username already exists!! try another"
    else:
        form=RegisterForm()
    return render(request,'register.html',locals())

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

13 Comments

I don't understand.. I already have a form.save() after if form.is_valid(). Shouldn't that work? The user.save() was used to save to update auth.User model.
That's exaclty what I mean. By doing form.save() the instance is saved directly in the db (with the form's data). After that, you are getting the form's data and create a new user. But this new user has been already created with form.save().
Oh! Now I get it. You have 2 separate models, UserDetails and Post which has a ForeignKey to User. My bad. Allow me to fix it, please.
Yes Sir, I have a UserDetails model and and a standard django.contrib.auth.User model what I tried to do was full the data from UserDetails modelform and use it to create a auth.User entry
Totally unrelated but your UserDetail model should have a OneToOneField on auth.User.
|
0

Age was missing in model form Fields

2 Comments

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
@Denis I'm the author

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.