Karena model Pengguna Django hanya memiliki beberapa bidang di dalamnya, saya membuat model khusus dan menggunakan ModelForm-nya untuk menyimpan data ke model Pengguna dan model khusus. The models.py adalah seperti yang ditunjukkan di bawah ini

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)

Bentuk model:

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

Views.py seperti ini

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())

Masalahnya adalah bahkan jika saya membuat entri baru ke RegisterForm, 'pesan' yang saya dapatkan adalah, nama pengguna sudah ada!! coba yang lain. Model auth.User diperbarui tetapi UserDetails tidak. Apa yang saya lakukan salah? (Lepaskan saya jika ini adalah pertanyaan bodoh :))

Pembaruan: 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())
0
AJAY AJITH 13 Maret 2017, 14:02

2 jawaban

Jawaban Terbaik

Usia tidak ada dalam bentuk model Fields

0
AJAY AJITH 13 Maret 2017, 15:11
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())

Lihat selengkapnya di ModelForm simpan() metode.

Namun, saya perhatikan bahwa bidang model age adalah required. Jadi, save() akan mengeluh. Sebaiknya Anda membuatnya sebagai: age = models.IntegerField(blank=True, null=True) atau menentukan nilai default seperti ini age = models.IntegerField(default=20). Meskipun, mendefinisikan usia default itu canggung, lebih baik ikuti blank=True null=True untuk mengizinkan age kosong.

1
nik_m 13 Maret 2017, 12:56