如何在Django中向Registrationform添加自定义用户模型?

时间:2017-04-14 15:39:27

标签: django forms model

这些天我做了很多研究但是没有完成它是如何完成的。 所以我有基本的User模型和Profile模型,如下所示:

class Profile(models.Model):
user = models.OneToOneField(User, null=True)
address= models.CharField(max_length=100)
posts = models.IntegerField(max_length=100)



@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
    Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()

my forms.py

class RegistrationForm(UserCreationForm):


class Meta:
    model = User
    fields = {'username','email', 'password1', 'password2', 'first_name', 'last_name'}



class UserProfileForm(forms.ModelForm):
class Meta:
    model = Profile

views.py

def register(request):
if request.method == 'POST':
    form = RegistrationForm(request.POST)


    if form.is_valid():
        user = form.save(commit=False)
        username = form.cleaned_data['username']

        user.save()
        user = authenticate(username=username)
        return redirect('/home')
else:
    form = RegistrationForm()

args = {'form' : form}
return render(request, 'home/reg_form.html', args)

那么我的代码中缺少什么才能让它出现在注册表单上?

感谢您的提前帮助

1 个答案:

答案 0 :(得分:1)

这就是我这样做的方式 views.py:

def register_user(request):
if request.method == 'POST':
        register = RegisterForm(request.POST, prefix='register')
        usrprofile = ProfileForm(request.POST, prefix='profile')
        if register.is_valid() * usrprofile.is_valid():
            user = register.save()
            usrprof = usrprofile.save(commit=False)
            usrprof.user = user
            usrprof.set_token()
            usrprof.subscribed = '1'
            usrprof.save()
            return HttpResponse('congrats')
        else:
            return HttpResponse('errors')
else:
    userform = RegisterForm(prefix='register')
    userprofileform = ProfileForm(prefix='profile')
    return render(request, 'registration/register_form.html', {'userform': userform, 'userprofileform': userprofileform})

模板:

<form action="" method="post">
    <div class="field">
        {{ userform.first_name.errors }}
        <label for="id_first_name">First name: </label>
        {{ userform.first_name }}
    </div>
    <div class="field">
        {{ userform.last_name.errors }}
        <label for="id_last_name">Last name: </label>
        {{ userform.last_name }}
    </div>
    <div class="field">
        {{ userform.email.errors }}
        <label for="id_email">Email: </label>
        {{ userform.email }}
    </div>
    <div class="field">
        {{ userform.username.errors }}
        <label for="id_username">Username: </label>
        {{ userform.username }}
    </div>
    <div class="field">
        {{ userform.password.errors }}
        <label for="id_password1">Password: </label>
        {{ userform.password }}
    </div>
    <div class="field">
        {{ userprofileform.address.errors }}
        <label for="id_address">Address: </label>
        {{ userprofileform.address }}
    </div>
    <div class="field">
        {{ userprofileform.city.errors }}
        <label for="id_city">City: </label>
        {{ userprofileform.city }}
    </div>
    <div class="field">
        {{ userprofileform.post.errors }}
        <label for="id_post">Post: </label>
        {{ userprofileform.post }}
    </div>
    {% csrf_token %}
    <input type="submit" value="Submit">
</form>

models.py(我使用内置的用户模型):

from django.db import models
from random import choice
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User)
    address = models.CharField(_('Address'), max_length=50, blank=True, null=True)
    city = models.CharField(_('City'), max_length=40, blank=True, null=True)
    post = models.CharField(_('Last name'), max_length=40, blank=True, null=True)
    token = models.CharField(_('Token'), max_length=15, unique=True, db_index=True, null=True)
    subscribed = models.CharField(_('Subscribed or not'), max_length=2, blank=True, null=True)

def set_token(self):

            self.token = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789') for i in range(15)])

def save(self, *args, **kwargs):
    super(Profile, self).save(*args, **kwargs)
    self.set_token()

forms.py:

from django import forms
from django.contrib.auth.models import User
from getall.models import Profile
from django.utils.translation import ugettext_lazy as _


class RegisterForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())

    class Meta:
        model = User
        fields = ['email', 'first_name', 'last_name', 'password', 'username']


class ProfileForm(forms.ModelForm):

    class Meta:
        model = Profile
        fields = ['address', 'city', 'post']