我尝试创建注册表单。它由几个从模型生成的表单 UserForm、UserProfileForm 和 CompanyForm 组成。
模型.py
from django.db import models
from django.contrib.auth.models import User
class Company(models.Model):
login = models.CharField(max_length=20, null=True)
password = models.CharField(max_length=10, null=True)
is_active = models.BooleanField()
title = models.CharField(max_length=100)
org = models.CharField(max_length=50)
inn = models.BigIntegerField()
kpp = models.BigIntegerField()
class UserProfile(models.Model):
company = models.ForeignKey(Company)
user = models.OneToOneField(User)
department = models.CharField(max_length=100)
position = models.CharField(max_length=100)
表格.py
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.forms import HiddenInput
from django.forms.models import modelformset_factory
from models import Company, UserProfile
class CompanyRegistrationForm(ModelForm):
class Meta:
model = Company
exclude = ('login', 'password', 'is_active')
class UserForm(ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email')
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
exclude = ('user')
widgets = {'company': HiddenInput()}
我尝试通过表单集和继承来做到这一点,但不幸的是。我想要一种具有一种自定义保存方法的表单,可以吗?
ps而我的views.py 是
class RegistrationCreateView(CreateView):
template_name = 'accounts/registration.html'
model = Company
#form_class = CompanyRegistrationForm
success_url = 'thanks/'
def _create_credentials(self):
login_str = random.randint(1000000, 9999999)
password = ''.join([symbol for i in range(10)
for symbol in random.choice(string.letters)])
return login_str, password
def form_valid(self, form):
context = self.get_context_data()
form = context['registration_form']
if form.is_valid():
#TODO(mid): refactor this
self.object = form.save()
company_id = self.object.id
login_str, password = self._create_credentials()
self.object.password = password
self.object.login = login_str
self.object.is_active = True
form.instance = self.object
form.save()
return self.success(login_str, password, company_id)
return self.form_invalid(form)
def form_invalid(self, form):
return self.render_to_response(self.get_context_data(form=form))
def get_context_data(self, **kwargs):
context = super(RegistrationCreateView, self).get_context_data(**kwargs)
context['registration_form'] = CompanyRegistrationForm()
context['user_form'] = UserForm()
context['user_profile_form'] = UserProfileForm()
if self.request.POST:
context['registration_form'] = CompanyRegistrationForm(self.request.POST)
context['user_form'] = UserForm(self.request.POST)
context['user_profile_form'] = UserProfileForm(self.request.POST)
return context
def success(self, login_str, password, company_id):
login(self.request, self.object)
self.request.session['company_id'] = company_id
return render_to_response('accounts/thanks.html',
{'login': login_str, 'password': password},
RequestContext(self.request))