非常感謝baylee對這個偉大的解釋。我能夠啓動並運行一些東西。我不完全確定這是否會被認爲是最佳做法?而且我也不確定這個方案是否存在安全漏洞或瓶頸,但它似乎在我的應用程序中運行良好。
models.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
height = models.CharField(max_length=24, blank=False,null=True)
weight = models.CharField(max_length=24, blank=False,null=True)
birthday = models.CharField(max_length=24, blank=False,null=True)
class Meta:
managed = True
db_table = 'user_profiles'
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
class UserContacts(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=24, blank=False,null=True)
phone = models.CharField(max_length=24, blank=False,null=True)
class Meta:
managed = True
db_table = 'user_contacts'
views.py
def add_contact(request):
if request.user.is_authenticated():
update_success = False
form = addContact(request.POST or None)
if request.method == 'POST':
if form.is_valid():
data = form.cleaned_data
contact = form.save(commit=False)
contact.user = request.user
contact.save()
form = addContact() #return blank form so user can continue adding to db
update_success = True
return render_to_response('contact_form.html',
{'update_success':update_success,
'form':form,
},
context_instance=RequestContext(request),
)
else:
return redirect('/accounts/login/')
forms.py
from django import forms
#Using Crispy forms helper object and bootstrap styling
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, ButtonHolder
from crispy_forms.bootstrap import TabHolder, Tab
#Using Models from "project.account" app
from accounts.models import UserContacts
class addContact(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(addContact, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.layout = Layout(
TabHolder(
Tab(
'Basic Information',
'name',
'phone',
),
),
ButtonHolder(
Submit('Save', 'Proceed', css_class='btn btn-lg btn-default')
),
)
class Meta:
model = UserContacts
fields = (
'name',
'phone',
)
謝謝大家!
@ Gman-O,我沒有代表評論你的答案,womp。但很高興你能工作! Re:最佳實踐/我的觀點,'managed'和'db_table'屬性通常保持默認。用Django 1。5+你不再需要UserProfile模型,你可以[創建一個自定義的'User'模型](https://docs.djangoproject.com/en/dev/topics/auth/customizing/#substitution-a-custom-user代替)。但是,嘿,如果它全部正常工作...... – baylee 2014-12-02 09:11:09